0

How can I provide a toggle for a dynamically created element? My code does not work:

JS

          $("body").on('toggle', ".buttonA", function(){
              function() {
                  ..do stuff
              },
              function() {
                  .. revert stuff
              }
      });
user1477955
  • 1,652
  • 8
  • 23
  • 35

2 Answers2

0

Try this:

$('body').on('click','.buttonA', function () {
var toggled = $(this).data('toggled');
$(this).data('toggled', !toggled);
if (!toggled) {
    //..do stuff
}
else {
   //.. revert stuff
}});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

If you are using jQuery,you can use .live() methods for binding a dynamically created element.

$('#hello').live("click", function() {
  alert( "Goodbye!" ); // jQuery 1.3+
});

I didn't use jQuery for a long time.So I don't know the method is valid or not.But it is very easy to write a new method to resolve this requirement.The more important thing is you bind the element whether or not.

CashLee李秉骏
  • 1,038
  • 1
  • 10
  • 23