스크립트 이벤트 질문점요 채택완료
초보적인 질문일수도있는데요~
동적 버튼 추가시 추가된 버튼 이벤트 할당위치 가르쳐 주실분 ㅠㅠ
Copy
<div id="test_wrap">버튼 추가 영역</div>
<button id="testBtn">버튼추가</button>
<script>
const testBtn = document.querySelector("#testBtn");
testBtn.addEventListener("click", ()=>{
let tmpBtn = document.createElement("button");
tmpBtn.id = "addBtn";
let btnTxt = document.createTextNode("추가버튼");
tmpBtn.appendChild(btnTxt);
document.querySelector("#test_wrap").appendChild(tmpBtn);
});
</script>
위는 테스트용이라 막코딩인데요...
버튼은 생성하겠는데... 안에있는 버튼에 이벤트를 추고 싶은데요
저럴때는 이벤트 위치를 어디다 해야하나요?
따로
$(function(){
});
이런거 만들어서 안에 추가 하는건가요?
자바스크립트는 할때마다 헷갈림 ㅠㅠ 가르침을 주실분~~
답변 1개
채택된 답변
+20 포인트
4년 전
Copy
const testBtn = document.querySelector("#testBtn");
testBtn.addEventListener("click", ()=>{
let tmpBtn = document.createElement("button");
tmpBtn.id = "addBtn";
let btnTxt = document.createTextNode("추가버튼");
tmpBtn.appendChild(btnTxt);
tmpBtn.onclick = function() { doSomething(); };
document.querySelector("#test_wrap").appendChild(tmpBtn);
});
const doSomething = () => {
console.log('추가버튼 클릭');
}
로그인 후 평가할 수 있습니다
답변에 대한 댓글 1개
포인트적립
4년 전
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인
tmpBtn.onclick = function() { doSomething(); };
이렇게는 안했지만....
답변 주신 내용중에서요...
tmpBtn.onclick = function() { doSomething(); };
이거 대신
doSomething(); 요거만 appendChild 밑에 넣어놓고 doSomething(); 이안에서
document.querySelector() 로 만들어진 애들 다시 불러와서 사용해도 상관없겠죠?