开发者

jQuery.click not binding on elements added with jQuery

开发者 https://www.devze.com 2023-01-09 16:25 出处:网络
I have a calendar where I can ad events to a list. It works like this: I click save, and data is saved to DB using jQuery.post

I have a calendar where I can ad events to a list. It works like this:

  1. I click save, and data is saved to DB using jQuery.post
  2. To refresh the list, I call getList() which returns a html list of events
  3. I replace the existing list with the new one.

The problem is, that the new element is added after page load, thus not binding.

I think I'm a bit confused on how to use jQuery bind or live Here is my code:

// New event - Form Submit
jQuery('#formNewEvent').bind('submit',function() {

    var formData = jQuery('#formNewEvent').serializeArray();

    jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'addNewEvent', formData : formData },
    function(data)
    {
      if(data == 1)
      {
        jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'getEventList' },
        function(list) {
            jQuery('#eventList').html(list);  // List is updated here
        });
      }       
    });
  return false; //Must have this - otherwise th开发者_JAVA技巧e page just goes blank (at least for me)
}); 

I know there are similar problems out there, but I've not been able to figure out the correct solution.


You just need to use live instead of bind so that newly added elements are also bound correctly.

jQuery('#formNewEvent').live('submit',function() {

    var formData = jQuery('#formNewEvent').serializeArray();

    jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'addNewEvent', formData : formData },
    function(data)
    {
      if(data == 1)
      {
        jQuery.post("/wp-content/plugins/wp-eventcal/eventcal_jquery.php", { instance: 'getEventList' },
        function(list) {
            jQuery('#eventList').html(list);  // List is updated here
        });
      }       
    });

});
0

精彩评论

暂无评论...
验证码 换一张
取 消