有很多方法可以实现您所需要的。这里有两个:
将点击处理程序分配给委托人父级
$("#table tbody").on("click", "tr", function() {
// get the tbody TR index and that's its position in the data array
const idx = $(this).index();
const row = data[idx];
myfunction(row);
});
或者
使用已分配的点击处理程序创建 TR
function populateResult(data, resultElementId) {
$.each(data, (i, row) => $("<tr>", {
html: `<td>${row.name}</td>`,
appendTo: resultElementId,
click() {
myfunction(row)
}
}));
}
最后一个例子的演示:
function populateResult(data, resultElementId) {
$.each(data, (i, row) => $("<tr>", {
html: `<td>${row.name}</td>`,
appendTo: resultElementId,
click() {
myfunction(row)
}
}));
}
function myfunction(shipObj) {
console.log("data :" + JSON.stringify(shipObj));
}
const data = [{name:"Lorem"}, {name: "Ipsum"}];
populateResult(data, "#myTableBody");
<table>
<tbody id="myTableBody"></tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>