开发者

How do I figure out when a table row is first or last using jQuery

I have a table where users can move items up or down by one. I'm trying to disable a Move Item Up By One and Move Item Down By One buttons when a table row reaches the top or the bottom (becomes first or last). I don't know how to determine when a <tr> Item has reached the top or the bottom of the table.

This is what I'm using at the moment, which handles swapping the table rows when an item has been moved up or down.

    $(".up,.down").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
    });

I want to add a nested if statement under the first if statement, and another if statement under the else condition of th开发者_StackOverflow社区e original if statement. The new conditional statements will be used to determine if the row has reached the top of the table, or the bottom of the table. I can then use this to enable/disable the buttons:

$(row).find('.up').find('input').attr('disabled','true');

The classes of the form buttons are up and down

So <form class="up"> <input type="submit"> </form> etc...

I'm not sure if this approach is the best, but I want to try it.


You can try using prevAll() and nextAll() on the tr. if those return no results, it means the said tr is either the first or the last child.

$(".up,.down").click(function(){
    var row = $(this).parents("tr:first");
    if ($(this).is(".up")) {
        row.insertBefore(row.prev());
        if(row.prevAll().length == 0){
           //you just moved a row to the top. this is where you disable the button
           row.find('.up').find('input').attr('disabled','true');
           //the row that was the top before had its up disabled, enable it
           row.prev().find('.up').find('input').removeAttr('disabled');
        } 
    } else {
        row.insertAfter(row.next());
        //do same kind of thing here with nextAll
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜