javascript - Onclick 将 setAttribute 动态添加到 td 元素将变量作为字符串传递
问题描述
我有一个动态创建的表格,其中一个单元格包含一个按钮。我使用 setAttribute 插入 onclick 事件,但它使用的变量是作为字符串而不是变量传递的。两点函数只是为传入的玩家添加点。它在静态表中工作,只是在我使用 setAttribute 方法时不行
eletble.setAttribute('onclick', 'TwoPoints(student1);');
解决方案
如果您有表格,请为每个学生使用一个单元格或行,并从 tbody 委托
const TwoPoints = student => console.log(student,"Two points");
document.getElementById("eletble").addEventListener("click", function(e) {
const tgt = e.target;
TwoPoints(tgt.dataset.student)
});
<table>
<tbody id="eletble">
<tr><td data-student="Student 1">Student number 1</td></tr>
<tr><td data-student="Student 2">Student number 2</td></tr>
</tbody>
</table>
推荐阅读
- php - 如何在 Laravel 中将策略功能与中间件一起使用?
- utf-8 - raku:支持 Raku 2020.10 中的 utf8-c8 问题
- javascript - 如何检查按钮是否被按下javaScript
- javascript - 如何在javascript中使用正则表达式替换字符串?
- python - 从python中的不同文件夹导入文件
- iterm2 - iterm2中暗模式和亮模式切换的快捷键?
- java - 如何解释 jeprof 输出
- python - 总结邻居数
- node.js - Angular CLI 不创建项目并且需要 npm@6
- javascript - Webp 不显示在服务器上