问题描述
我遇到了这种奇怪的行为。我想添加一个包含onclick行为的html模板。所以我尝试了下面的代码。问题在于其中的函数callFunction
是自动执行的。我的猜测是,callFunction
是在innerHTML中解析插值字符串时执行的。有没有解决此问题的方法?谢谢你
const container = document.getElementById("test1");
function callFunction() {
console.log('called');
}
container.innerHTML = `<button onClick="${callFunction()}"> Click on me</button>`
<div id="test1"></div>
解决方法
模板文字中的表达式将立即执行。如果要创建HTML字符串,则无需在与创建函数相同的范围内调用该函数。您甚至不需要模板文字。您只需要创建一个带有onClick
属性的字符串即可。
container.innerHTML = '<button onClick="callFunction()"> Click on me</button>'
const container = document.getElementById("test1");
function callFunction() {
console.log('called');
}
container.innerHTML = `<button onClick="callFunction()"> Click on me</button>`
<div id="test1"></div>