Click event doesn't fire for table rows added dynamically

亡梦爱人 提交于 2019-12-04 16:29:11

问题


I have an empty table to which I'm adding rows via jQuery using:

$('#table > tbody:last').append('<tr id="' + symbol.Code1 + '"><td>' + symbol.Code1 + '</td><td>' + symbol.Code2+ '</td><td>' + symbol.Code3+ '</td></tr>');

Everything is OK but when I implement:

$("#table tr").click(function(e) {
    alert(this.id);
});

nothing happens.


回答1:


You need event delegation you can use on to bind the click event for dynamically added elements. The way you are binding with click will apply on existing element but not elements which are added later.

$(document).on("click", "#table tr", function(e) {
    alert(this.id);
});

You can limit the scope for on by giving closest parent selector either by id or by class of parent.

$('.ParentElementClass').on("click", "#table tr", function(e) {
    alert(this.id);
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.




回答2:


You have to use the .on method

$("#table").on('click','tr',function(e) { 
    alert($(this).attr('id')); 
}); 



回答3:


You add rows dynamically after you have bound the event to the existing ones. You may use delegated event approach to fix the problem:

$("#table").on("click", "tr", function(e) {
    alert(this.id);
});



回答4:


$(document).on('click', "#tbl-body tr td", function(e) { 
    alert(this.id);
});


来源:https://stackoverflow.com/questions/13047169/click-event-doesnt-fire-for-table-rows-added-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!