jQuery与动态生成的元素 [英] jQuery with elements generated dynamically

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

问题描述

我已经使用jQuery一两周了,我注意到它与原始HTML文档中的对象一起正常工作,但是当我使用jQuery生成一个新元素时,库没有得到任何它的事件。

I've been working with jQuery for a pair of weeks and I've noticed it works fine with objects that are in the original HTML document, but when I generate a new element using jQuery the library doesn't get any of its events.

假设我尝试运行这样的事情:

Let's say I try to run something like this:

$('.whatever').click(function() {
  alert("ALERT!");
});

如果HTML确实有这样的内容:

If the HTML does have something like this:

<span class="whatever">Whatever</span>

然后点击单词无论让我一个很好的警报。

Then clicking on the word Whatever gets me a nice alert.

但是如果使用jQuery动态添加 span 元素,则点击它时没有任何反应。

But if the span element is added dynamically using jQuery, nothing happens when clicking on it.

有没有办法让jQuery能够以某种方式使用这些元素?

Is there a way to make jQuery work with those elements, somehow?

推荐答案

多数民众赞成因为:
(更正)

$('.whatever').click(function() {
  alert("ALERT!");
});   

表示字面意思:


Find all elements currently on the page that have the class ".whatever"
Foreach element in that result set, bind this function to its click event

所以很自然地,添加一个新的DOM元素不会自动应用点击。

so naturally, adding a new DOM element wont automagically apply the click.

解决此问题的最佳方法是在插入阶段创建绑定,即:

the best way to solve this is create bindings during your insert phase, ie:

  var x = document.createElement("span"); 
  $(x).click(function(){ });  //etc 
  $(somcontiner).append(x); 



警告简单重新绑定所有内容



如果做错了,它可能导致不良影响,即使事件触发事件增加的次数。要停止此操作,您可能需要首先取消绑定它们以删除先前的通行证绑定。

Warning on simply rebinding everything

If done wrong, it can lead to undesired effects, ie, making the number of times the event triggers something increase. To stop this, you may need to first unbind them to delete the previous passes binds.

ie,

$(x).click(foo); 
$(x).click(bar);  //foo and bar should both execute. 

所以要停止这个,你需要

so to stop this, you need

$(x).unbind("click");
$(x).click(foo); 

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

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