1

In my page, I use this block of code to generate HTML:

$.ajax({
        url: '...'
}).done(function (model) {
    for (var i = 1; i <= model.numberOfPages; i++) {
        html += '<a class="page_number" href="javascript:void(0);">'+i+'</a>&nbsp;';
    }
    $(".page_numbers").html(html);
});

But when I try to add a click event on these a tags, nothing happen. Where did I go wrong?

$(document).ready(function (event) {
    $('.page_number').click(function (event) {
        //Some code here
    });
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Empty Mind
  • 21
  • 1
  • 3

2 Answers2

2

You have to bind the events after you have added the elements to the page.

Or you can use a delegate instead, then you bind it to the parent element and specify which child elements it applies to:

$('.page_numbers').on("click", ".page_number", function (event) {
  //some code here
});

For jQuery 1.4.2 to 1.6.x you use the delegate method instead of the on method:

$('.page_numbers').delegate(".page_number", "click", function (event) {
  //some code here
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

As of jQuery 1.7, this is the is the way you bind an event to dynamically created objects

$(document).ready(function (event)
{
    $(document).on("click", ".page_number", function(e)
    {
       //some code here
    });
});

API Documentation: http://api.jquery.com/on/

Matías Cánepa
  • 5,770
  • 4
  • 57
  • 97