Javascript 如何在循环中设置onclick属性
我正在构建一个表格,第一列是文本,第二列是按钮。以下是完整的.js文件:Javascript 如何在循环中设置onclick属性,javascript,html,dom,Javascript,Html,Dom,我正在构建一个表格,第一列是文本,第二列是按钮。以下是完整的.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 = t
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);
如何在循环创建表时设置button onclick属性?您使用的是对函数中的
I
变量的引用,该变量将继续随循环变化,并且不会保留循环迭代时的I
值。您需要保留i
的当前值,可能需要将回调包装到另一个函数中:
cellElement.onclick = (function(currI) {
return function() { doThisThing(currI, ID[currI]); };
})(i);
您还可以使用bind
简化操作:
cellElement.onclick = doThisThing.bind(null, i, ID[i]);
我无法让第一个通过ID参数工作,但是,当只传递integer参数时,这是有效的。我不得不改变我原来的功能,但成功了,谢谢!你的回答中还有一个额外的“)”。
cellElement.onclick = doThisThing.bind(null, i, ID[i]);