我需要将行参数传递给我的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"]);};
返回循环中最后一次迭代的值...问题:如何在每次迭代中将值发送到click事件?
谢谢
最佳答案
将notification
捕获为匿名函数的参数。由于您似乎使用的是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
一起使用。