Jquery - 获取表中的上一个值行

时间:2013-05-08 15:54:23

标签: javascript jquery html

我有动态简单的表格,如:
 enter image description here

当我点击编辑按钮时,我尝试获取前一个值单元格。

例如:当我点击第一个将发出警报的编辑按钮('a1')
当我点击第二个编辑按钮时会发出警报('a2')

我尝试

$('.edit').click(function(){
        alert($(this).parents('tr').prev().children().eq(1).text());
});

它与第一个编辑按钮配合良好,因为上一行有一行 并且它不能使用第二个编辑按钮。

我该怎么做(按动态上一行) http://jsfiddle.net/bWjbj/

ps:我正在使用

处理下一行
alert($(this).parents('tr').nextAll(':eq(' + ($(this).parent().siblings().eq(0).attr("rowspan")-1) + ')').children().eq(1).text());

1 个答案:

答案 0 :(得分:4)

http://jsfiddle.net/mblase75/XGdkD/

问题是,对于第二个“编辑”按钮,前一个表行不是您想要的行 - 您希望在此之前有两行,因为这是行窗口开始的位置。

或者,通用:您希望属于上一个“编辑”按钮的表格行。但是,如果是第一个编辑按钮,则只需要上一行。

所以,在代码中:

$('.edit').click(function () {
    var idx = $('.edit').index(this); // which Edit button is this?
    if (idx > 0) { // first button
        var $tr = $('.edit').eq(idx-1).closest('tr'); // previous row
    } else { // not first button
        var $tr = $(this).closest('tr').prev('tr'); // previous Edit button's row
    }
    var $td = $tr.find('td:nth-child(2)'); // second <td> of the row
    alert($td.text());
});

相同代码的精简版:

$('.edit').click(function () {
    var idx = $('.edit').index(this),
        $tr = (idx) ? $('.edit').eq(idx-1).closest('tr') : $(this).closest('tr').prev('tr'),
        $td = $tr.find('td:nth-child(2)');
    alert($td.text());
});
相关问题