javascript - 如何在javascript中向onclick函数发送参数

标签 javascript onclick

我需要将行参数传递给我的 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/

相关文章:

javascript - Jquery onclick 这个删除两个跨度

javascript - knockout 模板 : afterRender triggered twice because name/data are coupled observables

javascript - 在 AngularJS 中删除输入值时如何再次验证表单

android - 在gridview中设置某些项目不可点击

javascript - 为什么复选框的 "checked"属性在单击事件时返回与其实际值相反的值?

javascript - 图像功能上的 Box-Shadow 不起作用

javascript - 使用 Restangular 并尝试将多个参数设置为 $scope 中的 var

javascript - 在 RenderingTemplate 中注册/包含 javascript

javascript - 如何在所有具有特定类的 dom 元素上添加 EventListener?

javascript - onclick=GA 代码给出服务器错误 500