George_Fal 2014-08-15 09:57 采纳率: 0%
浏览 3

Ajax和jQuery处理程序

I study Ajax and I have the problem.

For example, my markup is

<div id='ajax-container'>
  ..
  <div class='some-class-with-handler'>
    ..
  </div>
  ..
</div>

And I have the onClick-handler for .some-class-with-handler-block

$(document).ready(function() { 
  ..
  $('.some-class-with-handler').click(function(){
    ..
  });
  ..
}

Then Ajax overload everything in #ajax-container-block, but .some-class-with-handler-block is still included in the new content of #ajax-container-block. At the same time onClick handler isn't bind to the new .some-class-with-handler-block. How can I rebuild this binding?

  • 写回答

2条回答 默认 最新

  • weixin_33721344 2014-08-15 10:01
    关注

    Two choices:

    1. Use jQuery.live: http://api.jquery.com/live/

      Update: According to the doc, live is deprecated as of 1.7. You can use this syntax mentioned in the above doc:

      $( selector ).live( events, data, handler );                // jQuery 1.3+
      $( document ).delegate( selector, events, data, handler );  // jQuery 1.4.3+
      $( document ).on( events, selector, data, handler );        // jQuery 1.7+
      
    2. Rebind the click handler after AJAX

      var someClassClickHandler = function(){
          ..
      };
      
      $('.some-class-with-handler').click(someClassClickHandler);
      
      $.ajax({
          success: function () {
              $('.some-class-with-handler').click(someClassClickHandler);
          }
      });
      
    评论

报告相同问题?