jQuery函数不上加载asynchromously DOM元素工作 [英] jquery functions dont work on dom elements loaded asynchromously

查看:116
本文介绍了jQuery函数不上加载asynchromously DOM元素工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的的jQuery DOM 元素尚未在页面上,但可能会被异步加载到页面的事件处理程序。我观察到的是这些事件处理程序似乎没有认识到,一些新的元素添加到 DOM ,他们需要采取行动对他们的触发。

I wrote jQuery event handlers on DOM elements that are not yet in the page but might be loaded asynchronously into the page. What I observed was these event handlers seem to not recognize that some new elements were added to the DOM and that they need to act on them on triggering.

我的权利在我的观察?我该如何实现这个功能?

Am I right in my observation? How do I achieve this functionality?

推荐答案

如果您希望事件处理程序以动态地添加内容工作,你需要使用

If you want event handlers to work on dynamically added content, you need to use on

$(document).on("click", "someCssSelector", function(){
    //your code here
});

当然,这会导致所有的点击任何地方在网页上进行观看。为了更有效的,看看你是否可以组织你的网页,使所有这些因素,其对点击事件要处理将在一个集装箱。也就是说,如果所有这些元素都将被添加到一个div与的ID,你会写在上面更有效地

Of course this will cause all clicks anywhere on your page to be watched. To be more efficient, see if you can structure your page so that all of these elements whose click event you want to handle will be in one container. ie, if all of these elements are going to be added to a div with an id of foo, you'd write the above more efficiently as

$("#foo").on("click", "someCssSelector", function(){
    //your code here
});


如果您正在使用jQuery< 1.7,你会使用代理


If you're using jQuery < 1.7, you'd use delegate

$(document).delegate("someCssSelector", "click", function(){
    //your code here
});

这篇关于jQuery函数不上加载asynchromously DOM元素工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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