2017-05-14 21 views
0

所以基本上我面臨的問題是一些奇怪的jquery行爲的奇怪無法解釋。所以,讓我們說我有以下HTML:Jquery選擇器在輸入字段返回prevObject

<tr onclick='Clicked(this)'></tr> 

當我使用這樣的功能,一切,正在顯示的指標:

function Clicked(x) { 
    console.log(x); 
    console.log("Row index is: " + x.rowIndex); 
} 

輸出:

><tr onclick="Clicked(this)">...</tr> 
>Row index is: 1 

現在讓我們說,我不想直接註冊該行的函數,而是爲它的單元格中的輸入,而我想訪問該行的相同屬性。 一種行我表的樣本:

<tr> 
    <td> 
     <input type='text' class='immediate_update' value='myRandomVal'> 
    </td> 
</tr> 

現在我試圖從分配給等級的輸入的函數內部訪問的行和單元格屬性...這樣的:

$('.immediate_update').change(function(e) 
{ 
    var cell = $(this).closest('td'); 
    //I've also tried following, but it's returning the same: 
    //$(this).parent(); 
    var row = $(this).closest('tr'); 
    console.log(row); 
    console.log(row.rowIndex); 
}); 

輸出:

[tr, prevObject: yt.fn.init(1)] 
undefined 

,沒有該行的性質是工作...基本上,所以 我想問問你有什麼之間的差異的原因返回的對象以及訪問輸入所在單元格的行和列索引的方式 - 這就是我需要得到的結果......並且一般情況下的一些信息也是有用的,因爲我不知道怎麼了。提前致謝!

回答

1

rowIndex是一個純JavaScript,如果你需要使用它,你應該使用var row = $(this).closest('tr')[0];但在jQuery中您可以使用rowIndex

$('.immediate_update').change(function(e) 
 
{ 
 
    var cell = $(this).closest('td'); 
 
    //I've also tried following, but it's returning the same: 
 
    //$(this).parent(); 
 
    var row = $(this).closest('tr')[0]; 
 
    //console.log(row); 
 
    console.log(row.rowIndex); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
     <td> 
 
      <input type='text' class='immediate_update' value='myRandomVal'> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
      <input type='text' class='immediate_update' value='myRandomVal'> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
      <input type='text' class='immediate_update' value='myRandomVal'> 
 
     </td> 
 
    </tr> 
 
</table>

演示使用index()

使用 .index()

演示

$('.immediate_update').change(function(e) 
 
{ 
 
    var cell = $(this).closest('td'); 
 
    //I've also tried following, but it's returning the same: 
 
    //$(this).parent(); 
 
    var row = $(this).closest('tr'); 
 
    //console.log(row); 
 
    console.log(row.index()); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
     <td> 
 
      <input type='text' class='immediate_update' value='myRandomVal'> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
      <input type='text' class='immediate_update' value='myRandomVal'> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
      <input type='text' class='immediate_update' value='myRandomVal'> 
 
     </td> 
 
    </tr> 
 
</table>

就個人而言,我不喜歡混合純JavaScript和jQuery。而 ,而你已經包括jQuery的,你可以使用它,它很容易

+0

純缺乏知識就是我所遭受的......非常感謝!我需要的解釋類型。 –

+0

@ D.Petrov你完全歡迎..有一個偉大的日子:-) –