[英]Getting the value of the selected row and column in the table using 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列中顯示Im。
桌子的桌角,
<?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; ?>
這是因為更改觸發的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);
});
請注意:我認為獲取按鈕索引的最佳方法是:
var col = $('.sampleBtn').index(this);
代替:
var col = row.parent().children().index(row);
試試吧:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.