问题描述
我尝试以下代码:
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
alert(r);
var c = 0;
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
c++;
});
var btn = document.createElement("BUTTON");
btn.appendChild(document.createTextNode("نمایش"));
btn.setAttribute("id",r);
btn.setAttribute("class","tablebtn");
btn.setAttribute("onclick","myFunction(this.id)");
var cell1 = document.createElement('td');
cell1.appendChild(btn);
row.appendChild(cell1);
tableBody.appendChild(row);
r++;
});
但是myFunction(this.id)不起作用。它首先起作用。但是经过一些更改后,它不再起作用。请指导我。我探索了不同的解决方案
解决方法
不要为onclick设置属性
您可以直接设置属性:
btn.onclick = function(e) { myFunction(btn.id) }
或使用addEventListener
btn.addEventListener('click',function(e) { myFunction(btn.id) });
(您也可以直接设置ID,并使用btn.className ='tablebtn')