2012-01-12 68 views
15

我如何使用jQuery接入小区(td)立即低于在传统的网格布局HTML给定的细胞table(即,在其中的所有单元格跨越的具体哪一行和柱)?jQuery的:获取下一个表格单元格垂直

我知道,下面我们来设置nextCell到小区到单击的单元格的直接权利,因为他们是直接的兄弟姐妹,但我试图检索立即单击的单元格下面的单元:

$('td').click(function() { 
    var nextCell = $(this).next('td'); 
}); 

我最好不用任何类或ID。

回答

33

试试这个:

$("td").click(function(){ 
    // cache $(this); 
    var $this = $(this); 

    // First, get the index of the td. 
    var cellIndex = $this.index(); 

    // next, get the cell in the next row that has 
    // the same index. 
    $this.closest('tr').next().children().eq(cellIndex).doSomething(); 
}); 
+1

你不需要''td''参数给孩子,如果OP在表中有['th' elements](http://jsfiddle.net/nX7JP/),可能会抛出它。 – Dennis 2012-01-12 18:23:20

0

每个表格行中是否有相同数量的单元格?如果是这样,您可以得到有关单元的“计数”,然后在next('tr')中选择相应单元。

1

如何:

$('td').click(function() { 
    var nextCell = $(this).parent().next().find("td:nth-child(whatever)"); 
}); 
2
$('td').click(function() { 
    var index = $(this).prevAll().length 
    var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')') 
}); 

index是当前行中的单元格的从零开始的索引(prevAll找到所有的细胞中,这种一前)。

然后下一行中,我们发现nth-child TD索引+ 1(nth-child从1开始,因此+ 1)。

+1

为什么'$(this).prevAll()。length'超过'$ this.index()'? – 2012-01-12 18:16:29

+0

@JustinSatyr直到现在我还不知道有关'索引'。 :) – mbillard 2012-01-12 18:18:01

+1

我从来没有想过使用.prevAll()。长度。哈哈。同样的结果,我不知道哪一个更快。 – 2012-01-12 18:33:42

1

如果你想这样做,而不使用选择,你可以这样做:

function getNextCellVertically(htmlCell){ 
     //find position of this cell.. 
     var $row = $(htmlCell).parent(); 
     var cellIndex = $.inArray(htmlCell, $row[0].cells); 
     var table = $row.parent()[0]; 
     var rowIndex = $.inArray($row[0], table.rows); 

     //get the next cell vertically.. 
     return (rowIndex < table.rows.length-1) ? 
       table.rows[rowIndex+1].cells[cellIndex] : undefined; 
    } 

    $('td').click(function() { 
     var nextCell = getNextCellVertically(htmlCell); 
     //... 
    }); 

不是说效率是这里重要的,但它工作得更快做这样的 - 超过10万次迭代它在测试中比基于选择器的方法快2-5倍。

相关问题