createElement로 요소를 생성하지 않고 직접 html을 작성해서 innerHTML이나 jQuery의 append()와 같은 방법으로 요소를 동적으로 생성할 경우에는 이벤트 바인딩이 되지 않는다.
이런 경우에는 동적으로 생성된 요소의 부모 요소 중 동적으로 생성되지 않은 요소에 이벤트를 바인딩하면 된다.
<body>
<div class="parent"></div>
<button id="btn">클릭</button>
</body>
<script>
const parent = document.querySelector('.parent')
const btn = document.getElementById('btn')
let html = `
<div class="child">이 블럭은 초록색입니다.</div>
`
btn.addEventListener('click', () => {
parent.innerHTML = html
})
// const child = document.querySelector('.child')
// child.addEventListener('click', () => {
// child.style.backgroundColor = 'green'
// })
// => 이렇게 작성하면 요소를 찾을 수 없다고 나온다.
parent.addEventListener('click', (e) => {
e.currentTarget.children[0].style.backgroundColor = 'green'
})
</script>
[참고]
'웹 > 기타' 카테고리의 다른 글
JSP + Servlet 파일 업로드 (0) | 2023.10.01 |
---|