Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

javascript - Simple onload doesn't work in JSFIddle

http://jsfiddle.net/jzhang172/n5jb0159/

Simple document.body.onload event should trigger a javascript alert, but doesn't work but it works fine in my text editor -> browser. I switched the libraries around to jQuery to None (pure JS), still nothing, can someone explain to me what's going on and why it doesn't work in fiddle but works fine in my text editor?

This works:

  <body>
    Why
    <script>
  document.body.onload = function(){
      alert("LOADED!");
  }
  </script>
  </body>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your first problem:

Onload

You have configured JSFiddle to run your JS when the load event fires.

Consequently, when the load event fires, you bind another load event handler.

Your new load event handler is never called because the load event has already fired.

Change the menu option to one of the "No Wrap" approaches.


Your second problem:

The load event fires on the window object, not the body element.

You need to assign the property to the right place.

onload = function(){
  alert("LOADED!");
}

Such: https://jsfiddle.net/n5jb0159/5/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...