已有一個 `
// 返回從 0 開始的索引
var index = $(this).index();
<table id="demo">
<tr>
<td>第一列</td>
<td>第二列</td>
<td class="target">第三列</td>
</tr>
</table>
<script>
$('.target').click(function() {
// 獲取在父 tr 中的索引 (0-based)
var idx = $(this).index();
console.log('第 ' + (idx + 1) + ' 個 td'); // 輸出: 第 3 個 td
});
</script>
.index() **無參數時**:返回元素在**同類兄弟節點**中的索引位置// 父元素的所有單元格子節點
var allCells = $(this).parent().children('td, th');
var index = allCells.index(this);
var rowIndex = $(this).closest('tr').index(); // 0-based
var $td = $(this);
var col = $td.index();
var row = $td.closest('tr').index();
console.log('位置: 第' + (row+1) + '行, 第' + (col+1) + '列');
核心一行代碼:$(td元素).index() 即可獲取 0-based 列索引。