The general idea would be create the elements inside the function, assign event handlers to them, and then append them to the table:(通常的想法是在函数内部创建元素,为它们分配事件处理程序,然后将它们附加到表中:)
this.device.error_log.forEach((el, i) => {
if (el.message.component == "displays") {
const tr = document.createElement('tr');
tr.setAttribute('error_id', i);
tr.innerHTML = `
<td>
${this.device.error_log[i].message.component}
</td>
<td>
${this.device.error_log[i].message.info}
</td>
<button>
X
</button>`;
tr.querySelector('button').onclick = () => this.bam();
this.error_table.appendChild(tr);
}
});
Note that you should only use .map
when you need to create a new array.(请注意,仅在需要创建新数组时才应使用.map
。) Here, you want to perform side effects (alter the DOM), so you should use .forEach
instead.(在这里,您要执行副作用(更改DOM),因此应改用.forEach
。)
While it would be possible to change things around to use an inline handler instead, inline handlers are generally considered to be quite poor practice - they lead to fragile code, require global pollution, have string escaping issues, have scoping problems, and have a weird with
mechanism, among other things.(尽管可以改变周围的内容以使用内联处理程序,但是内联处理程序通常被认为是非常差的做法-它们会导致脆弱的代码,需要全局污染,存在字符串转义问题,具有范围问题以及很奇怪with
机制,等等。) Better to attach the listener explicitly.(最好显式附加侦听器。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…