简体   繁体   English

绑定多个动态添加的元素

[英]Binding More Than One Dynamically Added Elements

I'm using jQuery Mobile and I need to bind some tap events to dynamically added content. 我正在使用jQuery Mobile,并且需要将一些tap事件绑定到动态添加的内容。 It seems that the way I am doing it, my code only runs the last element I attach a tap event to inside my code. 看来,我这样做的方式是,我的代码仅运行我在代码内部附加了tap事件的最后一个元素。 For example, this code will not alert "Hi" when I click on element A but it will alert "Bye" when I click on element B. 例如,当我单击元素A时,此代码不会警告“ Hi”,但是当我单击元素B时,它将警告“ Bye”。

I'm sure this is a simple mistake but I've been banging my head against the desk trying to figure it out. 我敢肯定这是一个简单的错误,但我一直在想着解决办法,将头撞在桌子上。

$(document).off("tap").on("tap", "#A", function() {
    alert('Hi');
});

$(document).off("tap").on("tap", "#B", function () {
    alert('Bye');
}); 

It is because you are attaching the event to the document and then unbinding it in the next line. 这是因为您要将事件附加到文档,然后在下一行将其解除绑定。 So your binding on A is lost when you turn off tap on document and bind again on document for b. 因此,当您关闭对文档的tap并再次对文档进行b绑定时,您对A的绑定将会丢失。

Try: 尝试:

$(document).off("tap");
$(document).on("tap", "#A", function() {
    alert('Hi');
});

$(document).on("tap", "#B", function () {
    alert('Bye');
}); 

Also you can chain it though as well just to avoid creating jquery object again and again. 同样,您也可以将其链接起来,以避免重复创建jquery对象。

$(document).off("tap")
  .on("tap", "#A", function() {
    alert('Hi');
}).on("tap", "#B", function () {
    alert('Bye');
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM