3

我有动态的简单表,例如:
在此处输入图像描述

单击编辑按钮时,我尝试获取先前的值单元格。

示例:当我单击第一个编辑按钮时会发出警报('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());
4

1 回答 1

4

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

The problem is that for the second Edit button, the previous table row isn't the row you want -- you want the row two more before that, because that's where the rowspans begin.

Or, to be general: you want the table row belonging to the previous Edit button. In the case of the first edit button, though, you just want the previous row.

So, in code:

$('.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());
});

Compact version of the same code:

$('.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());
});
于 2013-05-08T16:10:00.743 回答