javascript - 使用 JQuery 从生成的表中检测单击表行

标签 javascript jquery html

我试图检测对表格行的点击,但我遇到了问题。该表是从一个 javascript 文件生成的,并放置在 html 中的一个 div 中。这个 div 被命名为“tableOutput”。如果我将它设置为“tableOutput”,我的 jquery click 功能将起作用,但我将其设置为“#myTable”或“#myTable tr”,它不会执行任何操作。有什么建议吗?谢谢!

生成表格的代码:

function loadUsers() {
$.getJSON("api/users", function(data) {
    var userTable = "\
        <table id=\"mt\" class=\"table table-hover\"><tr><th>User ID</th><th>User Name</th><th>Password</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Phone</th><th>DOB</th><th>Enabled</th></tr>";
    var count = 1;
    $.each(data, function(key, value) {
        userTable = userTable + "<tr id=\"tr" + count + "\"><td>" + value["userID"] + "</td><td>" + value["userName"] + "</td><td>" + value["password"] + "</td><td>" + value["firstName"] + "</td><td>" + value["lastName"] + "</td><td>" + value["email"] + "</td><td>" + value["phone"] + "</td><td>" + value["dateOfBirth"] + "</td><td>" + value["enabled"] + "</td></tr>";
        count = count + 1;
    });
    userTable = userTable + "</table>";
    $("#tableOutput").html(userTable);
}
);
}

检测点击的代码:

$(document).ready(function() {
$('#dp1').datepicker();
loadUsers();

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

最佳答案

你需要event delegation将事件绑定(bind)到动态添加的元素。因为你有表的静态父级,所以你可以将事件委托(delegate)给它。

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

委托(delegate)事件

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 docs

关于javascript - 使用 JQuery 从生成的表中检测单击表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22619012/

相关文章:

javascript - 从简单的模块模式迁移到 RequireJS AMD

javascript - iOS - 手动关注输入/文本区域的解决方法

javascript - 在 codeigniter 上使用 ajax 插入数据

html - 为什么我的最后一个跨度打破了我的 :after styling?

jquery - 我怎么知道有多少元素具有特定的背景颜色?

javascript - 从选定的 OrgChart 节点获取值 (Google orgchart)

javascript - 根据时区更改日历 View

javascript - 通过 AJAX 检索 PHP JSON 数据 - 数据请求的正确结构

html - 如何在 div 上模拟 onblur 事件

javascript - 显示 XML 文件中的数据