在javascript循环中添加.onclick侦听器[重复]

时间:2022-10-07 15:49:05

This question already has an answer here:

这个问题在这里已有答案:

I have a page getting JSON data via AJAX. I've managed to parse the data and create table rows from it. I'm now trying to add .onclick listeners to those rows using the following code:

我有一个页面通过AJAX获取JSON数据。我已经设法解析数据并从中创建表行。我现在正尝试使用以下代码将.onclick侦听器添加到这些行:

function addResultsRows(tbody, jsonResults) {
    for (var i in jsonResults) {
        var tableRow = tbody.insertRow(0);
        var currRow = jsonResults[i];
        tableRow.onclick = (function () {
            window.location = '/otherscript?cusnum=' + currRow['cusnum'];
        });
        var currCell = tableRow.insertCell(0);
        currCell.innerHTML = currRow['cusnum'];
    }
}

etc.

The problem I'm running into is that ALL of the rows are ending up with listener functions that use the currRow['cusnum'] value from the LAST row added to the table.

我遇到的问题是所有行都以监听器函数结束,这些函数使用添加到表中的LAST行中的currRow ['cusnum']值。

Javascript isn't (and won't likely ever be) my forte - only doing this because there isn't anyone else to do frontend code. Is the problem something to do with using an anonymous function in a loop?

Javascript不是(也不可能是)我的强项 - 只是这样做,因为没有其他人做前端代码。问题与在循环中使用匿名函数有关吗?

1 个解决方案

#1


Probably a change like

可能是变化之类的

function addResultsRows(tbody, jsonResults) {
    for (var i in jsonResults) {
        (function (i) {
            var tableRow = tbody.insertRow(0);
            var currRow = jsonResults[i];
            tableRow.onclick = (function() { window.location = '/otherscript?cusnum=' + currRow['cusnum'] });
            var currCell = tableRow.insertCell(0);
            currCell.innerHTML = currRow['cusnum'];
        })(i);
    }
}

would work.

In your scripts, i retains the value from the last iteration in the loop and is the same for all the event handlers.

在您的脚本中,我保留循环中最后一次迭代的值,并且对于所有事件处理程序都是相同的。

#1


Probably a change like

可能是变化之类的

function addResultsRows(tbody, jsonResults) {
    for (var i in jsonResults) {
        (function (i) {
            var tableRow = tbody.insertRow(0);
            var currRow = jsonResults[i];
            tableRow.onclick = (function() { window.location = '/otherscript?cusnum=' + currRow['cusnum'] });
            var currCell = tableRow.insertCell(0);
            currCell.innerHTML = currRow['cusnum'];
        })(i);
    }
}

would work.

In your scripts, i retains the value from the last iteration in the loop and is the same for all the event handlers.

在您的脚本中,我保留循环中最后一次迭代的值,并且对于所有事件处理程序都是相同的。