gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:41:12 27 4
gpt4 key购买 nike

我试图检测对表格行的点击,但我遇到了问题。该表是从一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com