Why evenlistener not working properly at jsfiddle?

泪湿孤枕 提交于 2019-12-13 01:36:39

问题


Please have a look at jsfiddle or here:

JS:

document.addEventListener('DOMContentLoaded', function myFunction() {
alert("Hello! I am an alert box");
}, false);

why this evenlistener not working? It should work because it works everywhere else. I think it's because of the iframe but I dunno...

Any idea?


回答1:


You have configured JS Fiddle to wrap your code in an onload event handler.

The sequence of events is:

  1. Load event handler is bound.
  2. DOM Content Loaded fires. There is nothing listening for it.
  3. Load event fires.
  4. Load handler executes and binds the DOM Content Loaded listener

You need to bind the event handler before the event it is listening for fires. Change the JS Fiddle options to one of the "no wrap" choices. Since you aren't touching anything in the DOM, it doesn't matter which of the two you select.




回答2:


Change load type to No wrap - in body

To change Load Type, click on label JAVASCRIP in script section, a pop will appears.

Updated Fiddle.

This might be because, by default, your script's load type in On Load, so all your script is loaded but your DOM is yet to render.



来源:https://stackoverflow.com/questions/35130982/why-evenlistener-not-working-properly-at-jsfiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!