Javascript – Adding jQuery .click() to dynamically created HTML


On my web app, I am dynamically creating a live feed using jQuery to parse a JSON object and dynamically creating table rows in html (see my earlier question here for an example )

Every table row I dynamically create from the JSON object, I add an image (using a standard html img tag) – What I want to do now, is create a .click() function that performs an async ajax call when that image is clicked.

so, if my code that creates the table rows dynamically looks like this:

var html = "<tr>"
            + "<td><img class=\"status_refresh\" src=\"/refresh.png\" id=\"refresh_id\"/></td>"
            + "</tr>";


In my JSP, where the peopleDirectory div is defined, and the html will be appended, I have the following javascript:

$('.status_refresh').click(function () { 

But nothing is happening when I click.. can anyone advise what I am doing wrong?


Best Solution

The click event is only bound to objects that exist at the time of binding. To bind the event to all existing and future objects, use the live method. Source Link

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

$('.status_refresh').live('click', function () {