2014-02-20 53 views
0

我有一個表單元格有一個可點擊的區域。當點擊那個區域時,我需要得到它的兄弟姐妹中的父細胞的索引。jQuery的索引來獲取父元素的位置

它看起來像jQuery's index function應該工作,不管傳遞的參數是一個jQuery對象還是一個DOM對象,但沒有一個返回我的示例中的預期結果。

任何想法我在這裏失蹤?

這是我歸結例如:

<table> 
    <tbody> 
     <tr> 
      <td><span class="a">Apricot</span></td> 
      <td><span class="b">Banana</span></td> 
      <td><span class="c">Cherry</span></td> 
     </tr> 
    </tbody> 
</table> 

<script src="http://code.jquery.com/jquery-1.10.2.min.js"/></script> 
<script> 
    $('span').click(function(){ 
     var jq_closestCell = $(this).closest('.td'); 
     var dom_closestCell = jq_closestCell[0]; 

     var jq_arrayCells = $('table tr td'); 
     var dom_arrayCells = jq_arrayCells[0]; 

     // This returns -1: 
     console.log(jq_closestCell.index(dom_arrayCells)); 

     // This returns -1: 
     console.log(jq_closestCell.index(jq_arrayCells)); 

     // Just for completeness, these obviously return 
     // an error ("Uncaught TypeError: Cannot call method 'index' of undefined") 
     console.log(dom_closestCell.index(dom_arrayCells)); 
     console.log(dom_closestCell.index(jq_arrayCells)); 
    }); 
</script> 
+0

是我的錯,我有'最接近(「TD‘)',而不是'最接近(’TD」)' –

回答

1

如果你想的td

var tdIndex = $(this).closest("td").index(); 

還是tr

指數
var trIndex = $(this).closest("tr").index(); 

小提琴:http://jsfiddle.net/YBp8H/

+0

的參數+1以明確您不需要將選擇器指定爲索引的參數 –

1

你只需要:

$('span').click(function() { 
    var jq_closestCellIndex = $(this).closest('td').index(); 
    console.log(jq_closestCellIndex); 
}); 
+0

+1要想清楚,你不需要指定選擇器作爲索引 –