jquery - 动态添加的表行不会触发单击事件

标签 jquery html-table click row addition

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

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

一切都很好,但是当我实现时:

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

没有任何反应。

最佳答案

您需要event delegation您可以使用 on 为动态添加的元素绑定(bind)点击事件。 您与点击绑定(bind)的方式将应用于现有元素,但不适用于以后添加的元素。

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

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

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

关于jquery - 动态添加的表行不会触发单击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13047169/

相关文章:

javascript - 快速移动鼠标不会触发 mouseleave

javascript - 悬停时父级内的目标标签

html - 构建小部件 (HTML/CSS)——表格还是 div?

events - Vue中如何在 “v-html”绑定(bind)点击事件

jquery - 单击 jquery + air 打开文件系统窗口

javascript - 表单重定向成功/失败页面

javascript - 使用串联将图像 url 设置为背景属性

html - 强制表行的高度与内容相同

javascript - 用 jQuery 删除表格行的最佳方法是什么?

css - 有没有可能用css做点击事件?