Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Why should $.click() be enclosed within $(document).ready()?

I am going through http://docs.jquery.com/How_jQuery_Works and find the requirement of enclosing $.click() event in $(document).ready() even a little strange. My difficulties are as follows:

  • When the document loads, the control will enter $(document).ready() function but will it proceed to execute $.click()? (Based on the behavior it wouldn't. But when the control enters a normal function, why wouldn't it enter $.click() function?)
  • Since the user can see the url only after the document is ready, is it really required to embed $.click() within $(document).ready()?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The How jQuery Works document uses the example of binding a .click() inside of $(document).ready() to be certain that the element to which the .click() event is bound has been created when the function executes.

The .click() called with a function as its parameter does not execute the .click() on the nodes matching its preceding selector, but rather binds the function to the matching nodes' onclick.

If you were to attempt to do something like this:

$('a').click(function(){
  alert('clicked me');
});

...in the document <head> or before any <a> element had been rendered, the event would not get bound to any node since no node matching the $('a') selector existed at the time the function executed.

Furthermore, if you did it when some <a> tags had been created, only those already created would get the bound event. <a> tags created after the function was bound wouldn't have the .click() binding.

So in jQuery (and other JavaScript frameworks), you'll often see the convention of adding event handlers, binding widgets, etc, inside a $(document).ready(function(){});


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...