当我在<script></script>
标签之间放置以下代码时,它会在页面加载时触发Test
函数,而不是触发mouseover
事件上的函数。为什么?
document.write(`<div id="test">some text</div>`);
document.getElementById("test").addEventListener("mouseover",Test());
function Test(){alert("mouseover");}
浏览器:Firefox Quantum 63.0.3
因为在将它分配给事件监听器时调用函数Test()
。这会调用函数 - 你只需要传递一个函数引用,这是函数的名称 - Test
:
document.write(`<div id="test">some text</div>`);
document.getElementById("test").addEventListener("mouseover", Test);
function Test() {
alert("mouseover");
}