2014-04-20 37 views
0

我有一系列的輸入列表內單元格,如電子表格。我只是試圖讓jquery找出他們在我開始輸入時所在的列。我想這樣做,而不必將標識符放在列中。jquery獲取另一個元素內的父元素的索引

http://jsfiddle.net/jx3FP/

我做了一對夫婦使用jQuery的指數的嘗試,但我明顯失去了一些東西。當我嘗試獲取表格數據(td)的索引時,我將其作爲文檔而不是其父文件。當我試圖指定父母和孩子時,索引似乎並不是一件好事。預先感謝您的幫助。

$('tr td input').live('keyup',function(e){ 
    /* attempt 1, returns nth td in document instead of the nth td in the table row 
    var column = $(this).parent().index('td'); 
    $('#column').val(column); 
    */ 
    /* attempt two */ 
    $parentRow = $(this).parents('tr'); 
    $parentCell = $(this).parent('td'); 
    var $column = $(this).parent('td').index('tr'); 
    // insert column number into #column 
    var $column = ($parentRow).index($parentCell); 
    $('#column').val($column); 
}); 
+0

更新您的提琴:http://jsfiddle.net/jx3FP/1/ –

回答

0

您正在尋找closest,不parentparents

var cellThisInputIsIn = $(this).closest('td'); 
var theCellsIndexWithinTheRow = cellThisInputIsIn.index(); 
var rowThisInputIsIn = $(this).closest('td'); 
var theRowsIndexWithinTheTableBody = rowThisInputIsIn.index(); 

目前尚不清楚你想一旦你擁有了它/它們與細胞/行和/或它們的索引做什麼,但是這是你如何找到它/他們。

0

的jsfiddle:http://jsfiddle.net/jx3FP/1/

HTML

<table> 
    <tr> 
     <td> 
      <input /> 
     </td> 
     <td> 
      <input /> 
     </td> 
     <td> 
      <input /> 
     </td>   
    </tr> 
    <tr> 
     <td> 
      <input /> 
     </td> 
     <td> 
      <input /> 
     </td> 
     <td> 
      <input /> 
     </td>   
    </tr>  
</table> 
<br /> 
<input id="column" placeholder="column" /> 
<input id="row" placeholder="row" /> 

JS

$('tr td input').live('keyup',function(e){ 
     /* attempt 1, returns nth td in document instead of the nth td in the table row 
     var column = $(this).parent().index('td'); 
     $('#column').val(column); 
     */ 
     /* attempt two */ 
     var cellThisInputIsIn = $(this).closest('td'); 
     var rowThisInputIsIn = $(this).closest('tr'); 
     var $column = cellThisInputIsIn.index(); 
     var $row = rowThisInputIsIn.index(); 
     $('#column').val($column); 
     $('#row').val($row); 
    }); 
+0

你能不能給我解釋一下嗎?爲什麼我的輸入的td父母(只有一個)與我最接近的td是一樣的? – daprezjer

+1

其實,最接近父母似乎並不像我想的那樣是一個問題,這只是我如何使用索引。我只需要改變: var column = $(this).parent()。index('td'); 至 var column = $(this).parent('td')。index(); – daprezjer

+0

@daprezjer好的。這真的很好解決方案。 –

相關問題