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>

最新更新