首页 > 解决方案 > Onclick 将 setAttribute 动态添加到 td 元素将变量作为字符串传递

问题描述

我有一个动态创建的表格,其中一个单元格包含一个按钮。我使用 setAttribute 插入 onclick 事件,但它使用的变量是作为字符串而不是变量传递的。两点函数只是为传入的玩家添加点。它在静态表中工作,只是在我使用 setAttribute 方法时不行

eletble.setAttribute('onclick', 'TwoPoints(student1);');

标签: javascriptonclicksetattribute

解决方案


如果您有表格,请为每个学生使用一个单元格或行,并从 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>


推荐阅读