简体   繁体   中英

Why can $(document).on(..) be placed anywhere on a page while $(“.cl”).on(..) has to be placed in the $(document).ready callback or after the <body>?

Title question says it all. For the most part, I understand the latter case. When the Javascript is read, the references to the DOM have to mean something, which is why we wrap it in the $(document).ready callback, or shaft our scripts under the <body> . I really don't understand why $(document).on(...) seems to work regardless of position.

Any input would be dope.

When you do $(anything) , the anything objects MUST exist at the time you run that selector.

When you're in the <head> section, the document object already exists as it's kind of the master parent for the whole page. But, nothing in the body exists yet so no $(“.class”) would exist yet and thus the selector would not find anything (or worse yet fail because the body doesn't even exist yet).

But $(document) does exist at the earliest time that you could possibly run scripts (in the <head> section so $(document) works and has something to attach the event handlers to.

If you are looking for elements in the <body> such as your example $(".class") , then you either have to wait for the <body> section to load with something like jQuery's .ready() (so those elements will exist before the script runs) or you have to physically place your script AFTER that element in the <body> so that the element you want has already been parsed by the time you run your script.


To add to this a little more, if you're using delegated event handling with .on() like this:

$(mySelector).on("click", ".myClass", fn);

Then the objects in $(mySelector) are what the event handlers will be directly attached to and those are what must exist at the time you run this line of code. The objects that match ".myClass" do not have to exist at the moment you run this code. So, if you do delegated event handling by attaching to the document object with:

$(document).on("click", ".myClass", fn);

Then, only the document object has to exist at the time you run this line of code. Since the document object is created first, it will already exist when you can run javascript code, thus it always seems to work.

This raises an interesting question about whether you can just attach all your event handlers to the document object. There are some tradeoffs if you do that (and some events only work properly if attached directly to the source object) so one shouldn't just blindly do that without understanding the consequences. See this answer for a more detailed discussion about tradeoffs in attaching all events to the document object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM