Language/Javascript
자바스크립트로 클래스 이벤트 추가하기
IFLA
2024. 2. 15. 14:19
개발을 하다보면 공통으로 사용하는 이벤트인 경우 클래스로 공통된 기능을 구현하고, 이벤트 리스너를 이용해 추가를 하면 공통된 기능을 어느 태그에서나 사용가능하다. 그래서 이번에는 클래스로 이벤트가 추가해 사용할 수 방법을 알려주려고 한다.
위의 화면은 파일 업로드/다운로드/삭제 기능이 있는 화면이다. 여기에서 삭제버튼이 공통된 삭제 기능을 가지고 있어서 삭제 기능을 클래스로 묶어서 구현으로 하려고 한다.
먼저 html 태그에 클래스에 삭제기능을 구현할 명칭을 추가한다.
<div class="row-6" th:each="item: ${files}">
<div class="card">
<div class="card-header" th:text="${item.id}"></div>
<div class="card-body">
<p class="card-text" th:text="${item.getOriginalName()}"></p>
<a th:href="@{/api/file/download/{id}(id=${item.id})}" class="btn btn-primary">다운로드</a>
<input type="button" th:value="삭제" class="btn btn-danger delete-btn" />
<input type="hidden" th:value="${item.id}"/>
</div>
</div>
</div>
<Input> 태그에서 type 이 button의 클래스에 delete-btn 을 추가했다. 자바사크립트에 이 클래스에 대한 기능을 추가한다.
const deleteBtn = document.getElementsByClassName('delete-btn');
for(let i=0; i<deleteBtn.length; i++) {
deleteBtn[i].addEventListener('click', function () {
const parentNode = this.parentNode;
const lastNode = parentNode.lastElementChild;
fetch(`/api/file/delete/${lastNode['value']}`, {
method: 'GET',
})
.then((response) => {
console.log(response);
alert('파일이 삭제되었습니다.');
location.replace('/fileList');
});
});
}
클래스 요소는 하나 일수도 있지만 보통은 여러 개 일수도 있다. 그래서 클래스 네임을 먼저 찾은 후 찾은 클래스의 사이즈만큼 이벤트를 추가해야한다.