2017-08-09 75 views
0

我試圖使用每個單元格中的按鈕來獲取所選行的列的值。這裏是我的Jquery,使用JQuery獲取表中選定行和列的值

$('.sampleBtn').click(function(){ 
    var row = $(this).closest('td'); 
    var col = $(this).parent().children().index($(this)); 
    var id = row.find('.mainId').val(); 
    var level = row.find('.level').val(); 

    alert("Main ID "+id+" Job ID "+col+" Level "+level); 
}); 

它正常工作時,我用了一個可點擊的細胞,但是當我使用一個按鈕,它總是說,即時通訊在第3列,即使我點擊其他單元格的按鈕。

鑑於表的TBODY,

<?php foreach($mains as $temp): ?> 
<tbody> 
    <tr> 
    <td> 
     <input type="hidden" value="<?php echo $temp->Main_ID; ?>"/><?php echo $temp->Main_Name; ?> 
    </td> 
    <td> 
     <select class="level"> 
     <option value="1">One</option> 
     <option value="2">Two</option> 
     <option value="3">Three</option> 
     </select> 
     <input type="hidden" class="mainId" value="<?php echo $temp->Main_ID; ?>" /> 
     <input type="button" class="sampleBtn" value="Update" /> 
    </td> 
    </tr> 
</tbody> 
<?php endforeach; ?> 

回答

1

那是因爲你還沒有改變觸發DOM元素之後更新$(this)引用。 this的按鈕範圍是<input>元素,對於該單元格,它是<td>。所以你需要更新腳本中的this引用。

$('.sampleBtn').click(function(){ 
    var row = $(this).closest('td'); 
    // Changed *this* to *row* below to point at the <td> 
    var col = row.parent().children().index(row); 
    var id = row.find('.mainId').val(); 
    var level = row.find('.level').val(); 

    alert("Main ID "+id+" Job ID "+col+" Level "+level); 
}); 
+0

哦,那就是我忘了..謝謝 :) – Vhey

0

只是注意:我認爲要獲得按鈕指數最好的辦法是:

var col = $('.sampleBtn').index(this); 

相反的:

var col = row.parent().children().index(row); 

試試:

https://jsfiddle.net/romadcxn/1/

相關問題