문제

I'm playing around with pagination and jQuery, my code first looked like this:

$(function() {
    $(".pagination a").live("click", function() {
        $.get(this.href, null, null, "script");
        return false;
    });
});

Then I noticed that live was removed in jQuery 1.9 so I changed my code to:

$(function() {
    $(".pagination").on("click", 'a', function() {
        $.get(this.href, null, null, "script");
        return false;
    });
});

But somehow this also won't work! The problem is that I can navigate from the first ajax page to the second but then form the second back to the first page or to the third page my ajax is not working. I supose because my code does not regognice the new added .pagination a.

도움이 되었습니까?

해결책

  • on is bound only for existing elements, if you want to make it listen to elements that were inserted after you use on you have to add a selector argument.
    With a selector argument it's a delegate event, while without it's a direct event.
  • If you used on delegate event signature the callback is bound to the selector which the on was called upon $('thisSelector'), while it will listen to the events of the elements in the selector argument like
    $('foo').on('event', 'thisSelector', func).
  • For better performance you should attach the on function to the closest static element to the newly inserted elements, this is actually the main reason why live was removed from jQuery in version 1.9, live attaches the listener to the document which has enormous performance penalty.

What we learned from the above, you must make sure .pagination is already in the DOM when you call on, and it shouldn't be replaced.

Now you should come with something like:

$("{staticElement-closeToTheNewElements}").on("click", '.pagination a',callback);

다른 팁

Could you try this?

$(function () {
    $(document).on("click", ".pagination a", function () {
        $.get(this.href, null, null, "script");
        return false;
    });
});

If you call:

$(document).on("click", '.pagination a', function(){...})

Should be:

$('#container-element').on("click", '.pagination a', function(){...})

it will call the event on any dynamically created element that matches the selector.

See above for optimal answer.

I'm hoping your html would like similar to this: If your div with class pagination is loaded via ajax it won't help by using it for event delegation since its not static.

 <body>
    <div id="static_div">
      <div class="pagination">
        <a href="" id="alink">I'm a link</a>
      </div>
    </div>
 </body>

Use

$('#static_div').on('click', '.pagination a', function(){...});

I'd suggest not to use body or document & use the closest static container to pagination for performance gain.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top