简体   繁体   中英

jquery on click selector attach on multiple elements

I usually handle click events for elements loaded with ajax like this:

$(document).on("click", ".selector", function () { ...}

But in a specific case where i load content multiple times, somehow $(document) doesn't work, instead only works if i attach it to parent $('.selector-parent').on("click", ".selector", function () { ...}

Depending on the case, there isn't always a parent selector. Is it possible to attach it to document, and if selector exists use it, something like:

$(document, '.selector-parent').on("click", ".selector", function () { ...}

I don't want to set any if else to search if parent element exists, but to use it like this.

You can simply do something like this:

$('.selector-parent').add(document).on("click", ".selector", function (e) {
    e.stopPropagation();
    console.log(e.delegateTarget);
});

Here is a little explanation. You select both parent element (which might not exist) and document into one collection using add method. After that you need to make sure event isn't handled twice by both .selector-parent and document , so whatever element processes it first, it stops event from further bubbling with e.stopPropagation(); .

As the result, if there is no parent .selector-parent as the ancestor of the clicked .selector , the document will handle event. If .selector-parent exists it will do the job and document will not be used.

Check the demo below for how it works for both situations.

 $('.selector-parent').add(document).on("click", ".selector", function (e) { e.stopPropagation(); alert(e.delegateTarget.nodeName); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="selector-parent"> <div class="selector">Parent exists</div> </div> <div> <div class="selector">No parent exists</div> </div> 

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