chaika_sv
chaika_sv

Reputation: 413

Ajax and jQuery handlers

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?

Upvotes: 0

Views: 154

Answers (2)

Junle Li
Junle Li

Reputation: 1035

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);
        }
    });
    

Upvotes: 2

sakibmoon
sakibmoon

Reputation: 2032

That's because the new .some-class-with-handler is a new element and you can't bind new elements this way. Change your handler this way -

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

Upvotes: 0

Related Questions