开发者

JQuery ajax and dom issue

开发者 https://www.devze.com 2023-01-12 14:10 出处:网络
I am using JQuery to add a row to a table.Within the row is an element who\'s click event I am capturing:

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&开发者_运维问答gt; ... </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?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号