为什么addEventListener会在另一个事件上触发函数(赋值给它)? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

当我在<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

javascript html html5 function dom
1个回答
1
投票

因为在将它分配给事件监听器时调用函数Test()。这会调用函数 - 你只需要传递一个函数引用,这是函数的名称 - Test

document.write(`<div id="test">some text</div>`);
document.getElementById("test").addEventListener("mouseover", Test);

function Test() {
  alert("mouseover");
}
© www.soinside.com 2019 - 2024. All rights reserved.