简体   繁体   中英

How can standard events fire on dynamically added elements? (JQuery)

I'm sorry for the poor wording on the title, if anybody can edit it to be more succinct and/or tell me what the proper terminology for what I'm looking for is, that would be great.

With dynamically added elements typical event binding doesn't work, but people claim the following does:

$('.elementClass').on('click',function() { });

I'm not having any luck with that, but of course this will always work:

$(document).on('click','.elementClass',function() { });

The problem is that will check the event every time the document is clicked, which obviously isn't very efficient. Is there a way of adding newly created elements into the flow so the following will still work on them?

$('.elementClass').click(function() { });

Thanks in advance for any help you can offer, and perhaps for informing me of the proper vernacular!

With dynamically added elements to bind events we have to use .on() . Avoid excessive use of document or document.body for delegated events on large documents.

Hierarchical selectors can often be avoided simply by attaching the handler to a more appropriate point in the document. For example, instead of $(document).on('click','.elementClass',function() { }); use $("#elementClass_parent_id").on('click','.elementClass',function() { });.

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