我遇到无法将事件 onclick 添加到我的元素的问题。如果我这样调用它:
<td onclick="${console.log('bam')}">X</td>
事件被立即调用,所以我假设如果我这样做的话:
<td onclick="${() => console.log('bam')}">X</td>
它会在点击后工作,但不幸的是,使用这样的代码它根本无法工作。任何人都知道如何解决它?哦,我希望在没有 jQuery 的情况下实现它。 完整代码:
this.device.error_log.map((el, i) => {
if (el.message.component == "displays") {
return (result += `
<tr error_id="${i}">
<td>
${this.device.error_log[i].message.component}
</td>
<td>
${this.device.error_log[i].message.info}
</td>
<button onclick="${() => console.log('bam)}">
X
</button>
</tr>`);
}
});
this.error_table.innerHTML += result
最佳答案
一般的想法是在函数内部创建元素,为它们分配事件处理程序,然后将它们附加到表中:
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);
}
});
请注意,只有在需要创建新数组时才应使用 .map
。在这里,您想要执行副作用(更改 DOM),因此您应该改用 .forEach
。
虽然可能改变使用内联处理程序来代替,但内联处理程序通常被认为是非常糟糕的做法 - 它们导致代码脆弱,需要全局污染,具有字符串转义问题,有范围问题,并且有一个奇怪的 with
机制,等等。最好显式附加监听器。
关于javascript - 将 onclick 事件添加到模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58911033/