2014-06-22 54 views
0

我需要将行参数传递给我的onclick函数。如何将参数发送到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"]);};正在返回在我的循环最后一次迭代值...

问题:我怎样才能把我的价值观到每次迭代的点击事件?

感谢

回答

0

我得到了它与下面的代码工作:

row.onclick = (function() { 
    var details = notification; 
    return function() { 
     showModalJobDetails(details); 
    } 
})(); 
1

捕捉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

+0

嗨@icktoofay感谢您的快速反应,你能告诉如何捕捉通知作为paremeter一个例子。我知道我正在使用jQuery,但我也在学习JavaScript。非常感谢 –

+0

@Manuel:我做到了;使用'$ .each'来做到这一点。如果你想在没有'$ .each'的情况下做到这一点,你可以用一个IIFE手动完成,例如'!function(someVariable){/ * ... * /}(someVariable)'。 – icktoofay

相关问题