develog

[jquery] 동적으로 append 한 element 에 click 이벤트 주기 본문

카테고리 없음

[jquery] 동적으로 append 한 element 에 click 이벤트 주기

냐옴 2021. 11. 5. 16:49

아래 코드는

  • 원래 있던 element 는 잘 동작함
  • append 로 추가한 element 는 동작하지 않음
$(".tag-wrapper .tag").click(function() {
    $(this).remove();
});

 

on 을 사용

  • 원래 있던 element 도 잘 동작함
  • append 로 추가한 element 잘 동작함
$(".tag-wrapper").on('click', '.tag', function() {
    $(this).remove();
});

HTML

<div class="tag-wrapper">
    <span class="tag">태그1</span>
    <span class="tag">태그2</span>
    <span class="tag">태그3</span>
</div>
Comments