[英]add onclick event to template
我有无法将事件 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
一般的想法是在function 中创建元素,为它们分配事件处理程序,然后将 append 分配给表:
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
代替。
虽然可以改变周围的事物以使用内联处理程序,但内联处理程序通常被认为是非常糟糕的做法 - 它们导致代码脆弱,需要全局污染,存在字符串 escaping 问题,范围界定问题,并且有一个奇怪的问题with
机制等。 最好明确地附加监听器。
很简单,您可以这样做:
<table> <tr> <td onClick="javascript: console.log('test')">test</td> </tr> </table>
或像这样:
<table> <tr> <td onclick=`${console.log('test')}`>test</td> <!–– Notice the backtick --> </tr> </table>
或者,甚至更简单:
<table> <tr> <td onClick="console.log('test')">test</td> </tr> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.