jQuery事件绑定动态加载的元素 [英] jQuery event binding with dynamically loaded elements

查看:88
本文介绍了jQuery事件绑定动态加载的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道并研究了多种绑定事件的方法 .on() .live() .click()等我知道 .live()在1.9+中已弃用。我遇到的问题是将动态DOM元素绑定到事件。

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.

我有一个包含链接的 div 是分页的。链接是使用AJAX动态加载的。我想覆盖这些链接的绑定事件,所以我使用 .unbind()并尝试 .on()。问题是这些动态加载的链接没有绑定。我想这是因为选择器 $('#id_of_links')与前一组链接一起缓存。

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 });

父树应该已存在于DOM树中...

Parent should already exist in the DOM tree...

更多信息: http://api.jquery.com/on/

这篇关于jQuery事件绑定动态加载的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆