2009-10-25 122 views
14

我是jQuery中的中間用戶。我知道使用jQuery來查找表的rowIndex,但我的場景是不同的。我的表(GridView)由20列組成,每列都有不同的控件,如文本框,下拉列表,圖像,標籤。所有是每行中的服務器端控件。我將gridview與數據庫中的記錄綁定在一起。現在,當我點擊任何文本框的任何控件或onchange時,我需要獲取該已更改列的行的rowIndex。這裏是我的用戶代碼:使用jQuery查找表格行索引

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){ 
    alert($(this).closest('td').parent().attr('sectionRowIndex')); 
}); 

但我無法獲取rowIndex。如果我在gridview中使用任何html控件,我可以得到rowIndex。當gridview中的服務器控件被點擊時,有什麼方法可以找到rowIndex?

回答

44

嘗試這種情況:

var rowIndex = $(this) 
    .closest('tr') // Get the closest tr parent element 
    .prevAll() // Find all sibling elements in front of it 
    .length; // Get their count 
+0

但我想要得到的改變文本框的rowIndex位置? – superachu 2009-10-25 11:50:22

+0

你能否提供你的頁面的HTML? – 2009-10-25 14:39:35

+0

​​ <跨度ID = 「gv1_ctl02_lblID」> 1 ​​ ​​ 當我點擊gv1_ctl02_txtName,我不會得到的rowIndex,但是當我點擊「txtLocation」,我可以得到。 – superachu 2009-10-25 15:34:48

4

這是表中的小區中的複選框時,有變化:

var row = $(this).parent().parent(); 
var rowIndex = $(row[0].rowIndex); 
console.log(rowIndex); 
9

sectionRowIndex<tr>元素的屬性,而不是一個屬性。

修改樣本代碼的正確方法是用零索引這樣訪問了jQuery項目:

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){ 
    alert($(this).closest('td').parent()[0].sectionRowIndex); 
}); 

這將返回正確的行索引爲您服務。另外,如果您打算使用jQuery的.closest()函數來遍歷DOM並且還要使用.parent(),爲什麼不編譯這兩個元素並只遍歷到最接近的<tr>元素?

$("#gv1 tr input[name $= 'txtName']").live('click', function(e){ 
    alert($(this).closest('tr')[0].sectionRowIndex); 
}); 

這也將處理奇怪的情況,其中父 - 子關係不完全符合您的預期。例如,如果你鏈接了一個$(this).parent().parent(),然後決定用另一個div或跨度包裹你的內部單元格,你可能會搞砸這個關係。 .closest()是確保它始終有效的簡單方法。

當然,我的代碼示例重新使用上面提供的示例。你可能希望先用一個更簡單的選擇器進行測試,以證明它的工作原理,然後優化你的選擇器。

1

應該能夠只使用:

var rowIndex = $(this).parents("tr:first")[0].rowIndex;