aeq
aeq

Reputation: 10547

JQuery ajax and dom issue

I am using JQuery to add a row to a table. Within the row is an element who's click event I am capturing:

$(document).ready(function() {
   var newRow = "<tr> ... </tr>";
    $('tableName > tbody:last').append(newRow);

   $(...).click( function() { // click event on newly inserted elem in the row
      alert("click");
   });
}

This works great and the alert comes up as expected. BUT when I now add the new row dynamically via an ajax call and parsing the xml, it stops working:

$(document).ready(function() {
   getData();

   $(...).click( function() { // click event on newly inserted elem in the row
      alert("click");
   });

   function getData() {
      $.ajax({
          ...
          success: function(data) {
             //parse the xml

             $('tableName > tbody:last').append(parsedXml);
          }
   });
}

The html is correctly added to the DOM, but the click event is no longer captured. Is there some issue with scope or closures going on here?

Upvotes: 0

Views: 633

Answers (3)

Ken Redler
Ken Redler

Reputation: 23943

When working with a table, I like to use .delegate() for this. It's very similar to .live(), but lets you set up an event listener on a single parent element, rather than individual handlers on every child element. So whether you have a table of one row or 1000, you still need only one handler.

$('#yourtable').delegate('your_descendant_element','click', function(){
   alert("click"); 
});

Upvotes: 1

g.d.d.c
g.d.d.c

Reputation: 47968

You should look into using the live() event handler. It allows you to create an event that matches elements created in the future dynamically, which is what is not happening right now. Another way to fix it would be to move the all to bind down below where you append the new table row, but live() is a much better answer.

Upvotes: 0

Stuart Burrows
Stuart Burrows

Reputation: 10814

use

 $(...).live('click', function() { // click event on newly inserted elem in the row
      alert("click");
   });

This keeps the click event running after it has been used

more info

Upvotes: 3

Related Questions