javascript,HTML,CSS
[javascript] Jquery click event not working after append method, 동적으로 생성된 태그 'append(html)'에 이벤트 주기
코린이예요
2019. 7. 24. 15:11
반응형
가령
js
let html = `<tr>
<td><input type="checkbox" name="checkbox" class="checkbox"></td>
<td>Gildong-Hong</td>
<td>1</td>
<td>07/24 2019</td>
</tr>`;
$("#information_tbl").find("table > tbody").append(html);
html
<div class="module-body" style="margin-left: 20px; padding: 0; min-height: 500px; " id="admin-ui-device-log">
<section>
<div style="max-height: 500px; overflow: auto">
<table id="information_tbl" class="table-hover _table-fixed">
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></th>
<th>Name</th>
<th>ID</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</section>
</div>
동적으로 ID가 'information_tbl'인 table에 td태그들을 append 한 후에 해당 html의 checkbox에 대한 click 이벤트를 jquery로 생성하려고 한다.
var tbl = $('#information_tbl');
$(":checkbox", tbl).click(function () {
....
});
처음에 이런식으로 했는데 아무 이벤트도 발생하지 않았다. 이렇게 동적으로 추가된 태그는 일반적인 이벤트가 동작되지 않는다.
해결방법은?
이벤트 위임(delegate)방식을 사용하는 것이다. '.delegate()'를 사용하면 되는데 이는 jquery 1.7부터 '.on()'으로 대체되었다.
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
참고
delegate : https://api.jquery.com/delegate/
on : https://api.jquery.com/on/
'.on()' method를 사용하여 해결할 수 있다.
$('#information_tbl').on('click', '.checkbox', function() {
...
});
Reference : https://stackoverflow.com/questions/15420558/jquery-click-event-not-working-after-append-method
반응형