jQuery 动态添加的表行不会触发 Click 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13047169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:14:49  来源:igfitidea点击:

Click event doesn't fire for table rows added dynamically

jqueryhtml-tableclickrowadd

提问by user1770849

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

我有一个空表,我使用以下方法通过 jQuery 添加行:

$('#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.

没发生什么事。

回答by Adil

You need event delegationyou can use onto bind the click event for dynamically added elements. The way you are binding with click will apply on existing elementbut not elements which are added later.

您需要事件委托,您可以使用来绑定动态添加元素的点击事件。您通过单击绑定的方式将适用于现有元素,但不适用于稍后添加的元素。

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

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

您可以on通过 id 或父类提供最接近的父选择器来限制范围。

$('.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.

委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件。通过选择在附加委托事件处理程序时保证存在的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要。

回答by Mihai Matei

You have to use the .onmethod

你必须使用.on方法

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

回答by VisioN

You add rows dynamically after you have bound the event to the existingones. You may use delegated event approachto fix the problem:

在将事件绑定到现有事件后,动态添加行。您可以使用委托事件方法来解决问题:

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

回答by khalid khuz nain

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