[英]How to send parameters to onclick function in javascript
我需要將行參數傳遞給我的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
使用委托。
我用下面的代碼工作:
row.onclick = (function() {
var details = notification;
return function() {
showModalJobDetails(details);
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.