2009-01-22 40 views
16

我試圖找到表中某一行的索引。我試圖使用下面的代碼,但我似乎得到-1的索引。如何使用jQuery查找表中某一行的索引

$(document).ready(function() 
{ 
    $("tr").click(function(){ 
     var index = $("table").index($(this)); 
     $("span").text("That was row index #" + index); 
    }); 
}); 

使用看起來像這樣的html;

<table> 
<tbody> 
    <tr><td>click</td></tr> 
    <tr><td>click</td></tr> 
    <tr><td>click</td></tr> 
    <tr><td>click</td></tr> 
</tbody> 

感謝

+0

var index = $(this).index(); – 2017-05-04 15:15:24

回答

31

你試過:

$("tr").index(this) 

文檔顯示剛好路過這個那個前面的選擇應該是一個節點被發現。如果你需要找到它在一個特定的表(有多個),你可能需要提供一些背景:

// haven't tested this 
$("tr", $(this).closest("table")).index(this) 
10

嘗試:

var index = $("table tr").index(this); 

index()文檔說:

搜索的 對象每個匹配的元素和返回 元素的索引(如果找到),從零開始。 如果傳遞了一個jQuery對象,則只檢查第一個元素 。

你需要調用index()<tr>元素,不是父<table>的集合。

+0

非常有意義。儘管如此,儘可能獲得-1。 – Winnemucca 2016-11-21 22:06:22

+0

@stevek我編輯了回答,在`this`附近刪除`$()`,因爲我不確定jQuery是否會在調用`$`時使用相同的節點實例返回相同的對象實例。 – 2016-11-22 13:05:56

2

基於剝奪答案找到索引特定的表,這個工作對我來說。

var index = $('tr', $(this).closest("table")).index(this);