我正在使用 DataTables 库来创建带有“下载”按钮的表。
在第一行,按钮可以工作,但在其余行则不起作用(我正在使用循环将数据输入到表中)。
我做错了什么?
JS 代码:
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
number = childData.Number;
table.row.add( [
number,
"<button id='script'>Download Files</button>"
] ).draw( false );
button = document.getElementById('script');
button.onclick = function(){ myScript(number)};
});
最佳答案
您创建了许多具有相同 id 的按钮,因此 document.getElementById('script');
将始终返回具有该 id 的相同第一个元素。
你可以尝试这样的事情:
snapshot.forEach(function(childSnapshot, i) {
var childData = childSnapshot.val();
number = childData.Number;
table.row.add( [
number,
`<button id='script${i}'>Download Files</button>`
] ).draw( false );
button = document.getElementById(`script${i}`);
button.onclick = function(){ myScript(number)};
});
关于javascript - DataTables 函数 - table.row.add ,不使用表内的按钮(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54666205/