2012-01-12 47 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倍。

相關問題