简体   繁体   中英

jQuery event binding with dynamically loaded elements

I know of and research multiple ways to bind events .on() , .live() , .click() , etc. I know .live() is deprecated in 1.9+. The problem I'm encountering is binding dynamic DOM elements to events.

I have a div that contains links and is paginated. The links are dynamically loaded with AJAX. I want to overwrite binded events for these links so I used .unbind() and tried .on() . The problem is that these dynamically loaded links are not binded. I guess that's because the selector $('#id_of_links') is cached with the previous set of links.

QUESTION : Is it possible to bind all elements that are loaded on the page, at any point in time, without having to set a callback when the user clicks next page on the links?

for dynamically added elements, you must bind the function to one of it's parents

$('#PARENT').on('click', '#DYNAMICALLY_ADDED_CHILD', function(){ CODE HERE });

Parent should already exist in the DOM tree...

More info on: http://api.jquery.com/on/

你不能绑定所有元素,即使那些没有加载到页面中的元素,没有回调方法/函数或循环的函数,并继续检查具有特定属性或特征的元素是否具有绑定到它的正确函数,这可能会导致内存泄漏。

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