当前位置: 动力学知识库 > 问答 > 编程问答 >

Jquery tr id selection

问题描述:

We are having 2 problem with jquery. Please have a look at the following...

We are using following table:

<tr id="row-5">

<td></td>

<td><a class="delete" href="#">Delete</a></td>

</tr>

And we are using following code:

$(function () {

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

var id = $(this).parents("tr").attr("id");

var info = 'id=' + id;

$.ajax({

type: "POST",

url: "delete.php",

data: info,

success: function () {}

});

return false;

});

});

So our questions are...

  1. How do we get the correct value of id(5) instead of row-5?
  2. Should we use each function on jquery code? If yes, how do we do that?

Thanks for your support.

网友答案:

Update:

Re your comment below:

i asked about each function because i am using jquery sortable and paging for 100 rows and delete button works great for first 10 rows but after that it changes url to #

That's because you're only hooking up the rows that already exist when the page is loaded. If you change your code to use delegate or live instead of click, it'll work with new ones added after:

$(function() {
    // Change is +--- here
    //           V
    $('.delete').live('click', function() {
        var id  = $(this).closest("tr").attr("id");
        id = id.substring(4); // or .split('-')[1] as suggested by other answer
        var info = 'id='+id;
        $.ajax({
            type: "POST",
            url: "delete.php",
            data: info,
            success: function(){
            }
        });
        return false;
    });
});

bind (click is just a shortcut for bind) hooks up the handler to elements that already exist. When you use a paging plug-in, the other elements aren't there yet, so they won't get hooked up. delegate and live work differetly: They take advantage of event bubbing and hook the event on a container element (live uses the root of the document, delegate uses whatever you tell it to use). See the linked docs for details. If you can use delegate rooted in the container table, do that in preference to live.


Original answer:

attr is giving you the correct value ("row-5"). If you want to extract just the "5" from that, you can use substring:

id = id.substring(4);

I'm not seeing anywhere you'd need to loop.


Off-topic: You can also save the browser a bit of work by using closest rather than parents.

$(function() {
    $('.delete').click(function() {
        var id  = $(this).closest("tr").attr("id");
        var info = 'id='+id;
        $.ajax({
            type: "POST",
            url: "delete.php",
            data: info,
            success: function(){
            }
        });
        return false;
    });
});
网友答案:

1 - var id = $(this).closest("tr").attr("id").split("-")[1];

2 - No need, since the row you are selecting is the closest parent row to the clicked anchor.

分享给朋友:
您可能感兴趣的文章:
随机阅读: