Javascript“addEventListener”事件在页面加载时触发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2373995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:59:12  来源:igfitidea点击:

Javascript "addEventListener" Event Fires on Page Load

javascriptjavascript-eventsaddeventlistener

提问by Russ Bradberry

When I run the following script, the event always fires on page load. I am not sure what I am doing wrong here, I create the element, find it in the DOM then attach a listener, but it always fires the event when the page loads and not when the element is clicked.

当我运行以下脚本时,事件总是在页面加载时触发。我不确定我在这里做错了什么,我创建了元素,在 DOM 中找到它然后附加一个侦听器,但它总是在页面加载时而不是在单击元素时触发事件。

<script type="text/javascript" language="javascript">
    document.write("<div id=\"myDiv\">I am a div</div>");
    el = document.getElementById("myDiv");
    el.addEventListener("click", alert("clicktrack"), false);
</script>

回答by kennytm

el.addEventListener("click", alert("clicktrack"), false);

When this line is executed, the alertwill be called and return undefined. To pass the alert code you need to wrap it in a function.

当这一行被执行时,alert将被调用并返回undefined。要传递警报代码,您需要将其包装在一个函数中。

el.addEventListener("click", function() { alert("clicktrack"); }, false);

回答by Sani Singh Huttunen

How about:

怎么样:

<script type="text/javascript" language="javascript">
  document.write("<div id=\"myDiv\">I am a div</div>");
  el = document.getElementById("myDiv");
  el.addEventListener("click", function() { alert("clicktrack"); }, false);
</script>