🏆토이 프로젝트에서 생긴 일
[Spring] mustache에서 어떤 버튼이 클릭 되었는지 아는 방법 (target 인식)
pkyung
2023. 9. 30. 00:10
반응형
안녕하세요.
토이 프로젝트에서는 백엔드만 하는 것이 아닌 프론트도 하기 때문에 (대략 그림 그리기정도지만^^) 고려해야할 점이 참 많습니다.
그 중 곤욕을 조금 겪었던 게 있는데 소개 해볼까합니다.
머스타치에서 button이 클릭되면 아래 js 파일로 가 ajax를 통해 값을 보내줘야합니다.
그런데 버튼이 여러 개이기 때문에 어떻게 해야하지? 싶었습니다.
{{#friends}}
<tbody>
<tr>
<td>{{name}}</td>
<td>{{uuid}}</td>
<td><button value="{{uuid}}" type="button" class="btn btn-outline-secondary">친구 요청</button></td>
</tr>
</tbody>
{{/friends}}
let button = document.getElementById("request");
let friendId = document.getElementById("request");
button.onclick = function () {
$.ajax({
type: "POST",
url: `/friend/request/${friendId.value}`,
})
button.disabled = true;
}
이 것도 꼼수를 써서 button의 value 값에 친구의 uuid를 넣어놓고 button id를 가져와서 클릭되면 서버로 보내지게 만들었습니다.
그런데 이렇게 되면 첫번째 버튼만 인식이 됩니다. 왜냐하면 id로 객체를 받았기 때문입니다.
그래서 event.target을 써보기로 했습니다.
onclick을 해서 함수를 불러봤는데 왜인지 인식이 되지 않았습니다.
<td><button onclick="click(this)" value="{{uuid}}" type="button" class="btn btn-outline-secondary">친구 요청</button></td>
function click(e) {
console.log(e.target);
}
그래서 모든 버튼을 querySelectAll로 받아온 뒤, forEach() 로 모든 버튼에 addEventListener를 넣어줬습니다. 그 이벤트 리스너에는 클릭이벤트를 넣어 어떤 버튼이 클릭이 되었는지 받아오고 그 안의 value 값을 가져오는 방식으로 해결했습니다.
document.querySelectorAll(".btn").forEach(function (button) {
button.addEventListener("click", function (event) {
let friendId = event.target;
console.log(friendId)
$.ajax({
type: "POST",
url: `/friend/request/${friendId.value}`,
})
button.disabled = true;
})
})
이제는 두 번째 버튼을 눌러도 잘 인식되어 친구 추가가 됩니다.
반응형