在 javascript 循环中添加 .onclick 侦听器
Adding .onclick listeners in javascript loops
我有一个页面通过 AJAX 获取 JSON 数据。我已经设法解析数据并从中创建 table 行。我现在尝试使用以下代码向这些行添加 .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'];
}
}
等等
我 运行 遇到的问题是,所有行都以使用添加到 table 的最后一行中的 currRow['cusnum']
值的侦听器函数结束。
JavaScript 不是(而且永远不会是)我的强项 - 这样做只是因为没有其他人可以编写前端代码。问题与在循环中使用匿名函数有关吗?
可能是
这样的变化
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);
}
}
会起作用。
在您的脚本中,i
保留循环中最后一次迭代的值,并且对所有事件处理程序都相同。
我有一个页面通过 AJAX 获取 JSON 数据。我已经设法解析数据并从中创建 table 行。我现在尝试使用以下代码向这些行添加 .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'];
}
}
等等
我 运行 遇到的问题是,所有行都以使用添加到 table 的最后一行中的 currRow['cusnum']
值的侦听器函数结束。
JavaScript 不是(而且永远不会是)我的强项 - 这样做只是因为没有其他人可以编写前端代码。问题与在循环中使用匿名函数有关吗?
可能是
这样的变化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);
}
}
会起作用。
在您的脚本中,i
保留循环中最后一次迭代的值,并且对所有事件处理程序都相同。