我需要将行参数传递给我的 onclick 函数。
这是我的代码:
function renderHostTableRowJob (dataTable) {
for (var i in dataTable) {
var notification = dataTable[i];
var row = document.createElement("tr");
var cell = document.createElement("td");
cell.innerText = notification["Name"];
row.appendChild(cell);
var cell = document.createElement("td");
cell.innerText = notification["State"];
row.appendChild(cell);
var cell = document.createElement("td");
cell.innerText = (notification["NotificationReceived"] === true) ? "Received" : "Missing";
row.appendChild(cell);
row.onclick = function() {alert(notification["Name"]);};
$("#" + notification["Client"] + "_TableJobDetails > #" + notification["Client"] + notification["HostFormated"] + "_TableBodyJobDetails")[0].appendChild(row);
}
}
目前,我的所有 row.onclick = function() {alert(notification["Name"]);};
都返回循环中最后一次迭代的值...
问题:如何将我的值发送到每次迭代的点击事件?
谢谢
最佳答案
捕获通知
作为匿名函数的参数。由于看起来您正在使用 jQuery,因此您可以使用 jQuery.each
,这将简化您的迭代并作为副作用捕获它:
$.each(dataTable, function(index, notification) {
// ...
});
顺便说一句,如果您使用 jQuery,您可以更简洁地编写代码:
var row = $('<tr>').click(function() {
alert(notification.Name);
});
$('<td>').text(notification.Name).appendTo(row);
$('<td>').text(notification.State).appendTo(row);
$('<td>').text(notification.NotificationReceived ? 'Received' : 'Missing').appendTo(row);
row.appendTo('#' + notification.Client + '_TableJobDetails > ' +
'#' + notification.Client + notification.HostFormated + '_TableBodyJobDetails');
此外,如果您的 ID 是唯一的(理应如此),则无需指定整个层次结构;只需使用
row.appendTo('#' + notification.Client + notification.HostFormated + '_TableBodyJobDetails');
此外,虽然代码中的更改较大,但请考虑使用 on
的委托(delegate)。 .
关于javascript - 如何在javascript中向onclick函数发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24349048/