简体   繁体   中英

Why does jQuery behave differently than javascript?

I'm new to jQuery and wrote the following code. Strangely, the jQuery code somehow works even after the time delay. alert() gets called onclick after the time delay. The same thing in javascirpt with .addEventListener() would give error since the element doesn't exist. Can someone explain me how and why jQuery does this?

<div id="outerId" class="outerHolder">
  <div class="innerHolder"></div>
</div>

JS Code:

$("#outerId").on("click touchstart", "#newTag", function (e) {
    alert("OK");
});

setTimeout(function() {
    var tag = '<div id="newTag">Hello World</div>';                  
    $("#outerId").append(tag);
}, 5000);

Here is a jsFiddle of the same: https://jsfiddle.net/jb6pmovb/

If you are wondering how the click works on an element which is not there at the time of page load, then that's because you are attaching the listener on the outerDiv and using .on

Check out this for the difference between using .on and .click

My guess is that your query is about the way on() is binding to to the object. When on() is first ran, #newTag does not exist, so you might be wondering why it still triggers when appended after a delay.

This is because #outerId is the object being bound to, which does exist the time on() is called. When you append #newTag , it doesn't alter the outer binding, it simply looks over the children when it is clicked.

With regular js I assume you are using addEventListener , which requires you bind the event to the specific object. If you do try and use that directly on #newTag before it exists, it obviously won't work.


You can see by the docs for on() :

selector

Type: String A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

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