如何在循环中设置onclick属性

how to set onclick attribute in a loop

我正在构建一个 table,第一列是文本,第二列是按钮。这是完整的 .js 文件:

var table = document.createElement("table");
var tableBody = document.createElement("tbody");

for(i = 0; i < array.length; i++) {

var row = table.insertRow(i);
var cell = row.insertCell(0);
cell.innerHTML = text[i];

var cell = row.insertCell(1);
var cellElement = document.createElement("input");
cellElement.setAttribute("id", ID[i]);  
cellElement.setAttribute("type", "button");
cellElement.setAttribute("value", "button");

/////cellElement.onclick =
     /////function(){ doThisThing(i,ID[i]); } );

cell.appendChild(cellElement);
row.appendChild(cell);

}

table.appendChild(tableBody);

document.body.appendChild(table);

除 cellEllement.onclick = function(){} 外一切正常; onlick() 函数未设置。我试过这方面的变化:

cellElement.setAttribute("onclick",doThisThing(i,ID[i]));

如何在循环创建按钮时设置按钮的 onclick 属性 table?

您在函数中使用了对 i 变量的引用,该变量将随着循环不断变化,并且不会保留它在您执行时所具有的 i 的值通过循环的迭代。您需要保留 i 的当前值,可能是通过将您的回调包装在另一个函数中:

cellElement.onclick = (function(currI) {
   return function() { doThisThing(currI, ID[currI]); };
})(i);

您还可以使用 bind 使事情变得更简单:

cellElement.onclick = doThisThing.bind(null, i, ID[i]);