简体   繁体   中英

Binding More Than One Dynamically Added Elements

I'm using jQuery Mobile and I need to bind some tap events to dynamically added content. 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. 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.

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.

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.

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

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