Javascript “addEventListener” Event Fires on Page

2019-01-01 02:31发布

This question already has an answer here:

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.

<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>

2条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 03:00

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>
查看更多
倾城一夜雪
3楼-- · 2019-01-01 03:08
el.addEventListener("click", alert("clicktrack"), false);

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

el.addEventListener("click", function() { alert("clicktrack"); }, false);
查看更多
登录 后发表回答