首页 > 解决方案 > DataTables function- table.row.add ,不使用表格内的按钮(javascript)

问题描述

我正在使用 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)};
});

标签: javascriptdatatabledatatables

解决方案


您创建了许多具有相同 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)};
});

推荐阅读