我试过这个:
const el = `<button class="create-panorama" onclick="${test()}">Create panorama</button>`
function test () {
console.log('esesesee')
}
element.insertAdjacentHTML('beforeend', el)
// element = <div id="element"></div>
但是,当我点击按钮时没有任何反应。
向 button
添加点击 Action 的最佳方式是什么?
最佳答案
onclick="${test()}"
这基本上是尝试执行:
${test()}
这显然行不通,因为您不能在字符串外部使用模板文字。因此就做
onclick="test()"
What's the best way to add a click action to button?
内联事件监听器由于一些原因是不好的,总是使用 .addEventListener
!
const el = document.createElement("button");
el.textContent = "Click me!";
el.className = "sth";
el.addEventListener("click", test);
element.appendChild(el);
关于javascript - 如何将函数/事件监听器添加到使用 ES6 模板文字创建的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50018368/