简体   繁体   中英

jquery using $.on for added dom elements?

I am a bit confused, I have a bunch of elements that get added via jquery using a ajax call and I want to attach a click handler to them (there could be a lot).

But I have no idea how to even begin this, I looked at .on and it is really confusing. I want to attach a click event handler for a certain class so that when I click on it, I get the this.id and then do stuff with it.

What you're trying to do is called event delegation.

You want to set the event listener on a higher element in the DOM that'll never change, but only fire off the event handler if the child element that has been clicked matches a specific selector.

Here's how it's done with jQuery's .on() :

$(document).on('click', '.your-selector', function(){
    alert(this.id);
});

PS You could probably apply the event listener to an element lower down in the DOM tree...

This will get you the id of a clicked element with the class "test"...

$(".test").on("click", function() {
    var id = $(this).attr("id")
});

You'll need to run that after the ajax call returns. It will only bind the click event to elements that exist when it runs, so it's no good at document.ready.

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