且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery查找动态生成的tr标记的ID

更新时间:2023-12-05 12:06:58

您可以执行以下操作:

$("a[href='delete.php']").click(function(e){
   var tr = $(this).closest('tr'),
       id = tr[0].id;

   // Put your AJAX call here
   $.post('/delete/' + id, function(){
       // Animate up, then remove
       tr.slideUp(500, function(){
          tr.remove();
       });
   });

});

closest() 在DOM树中向上移动,以查找与选择器匹配的祖先.在这种情况下,我们正在寻找第一个tr.我还可以使用 parent() 并获得相同的结果.

i have a table with tr containing 10 td elements. The tr are generated dynamically. For eg

<tr id = "<?php echo $count; ?>" >

<td>name </td>
<td>info </td>
...
...
<td><a href="delete.php">delete</a></td>

</tr>

What i wish to do is when i click on delete link , using ajax go to delete page do the needful and then without page refresh delete the row.

My problem is how do i get the ID in jquery? or is there any other way i could work out but i wish to use jquery for this particular purpose. Thanks

You could do this:

$("a[href='delete.php']").click(function(e){
   var tr = $(this).closest('tr'),
       id = tr[0].id;

   // Put your AJAX call here
   $.post('/delete/' + id, function(){
       // Animate up, then remove
       tr.slideUp(500, function(){
          tr.remove();
       });
   });

});

closest() travels up the DOM tree looking for an ancestor that matches the selector. In this case, we were looking for the first tr. I could have also used parent() and gotten the same result.