3 回答

TA貢獻1772條經驗 獲得超8個贊
您可以使用函數index
的參數each
。 https://api.jquery.com/each/
$(document).ready(function(){
$("#usersTable tr").click(function(){
$(this).find("td").each(function(index){
if (index === 0) {
console.log($(this).html());
}
});
});
})
如果您不需要其他td
元素,請不要循環!最好使用下面這個解決方案。

TA貢獻1828條經驗 獲得超13個贊
您可以使用這樣的選擇器,這樣您就不必循環選定行的所有單元格
$(document).ready(function() {
$("#usersTable tr").click(function() {
console.log($(this).find("td:first-child").html());
});
});

TA貢獻1848條經驗 獲得超10個贊
我已經重構了您的 HTML 結構并更新了 javascript 代碼。
$(document).ready(function() {
$('tbody tr').on('click', function() {
let firstTd = $(this).find('td:first-child');
let userId = firstTd.text();
console.log(userId);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="usersTable">
<div id="div2">
<thead>
<tr id="tableHeadings">
<th>User ID</th>
<th>Email</th>
<th>Forename</th>
<th>Surname</th>
<th>Avatar</th>
</tr>
</thead>
<tbody id="tableBody">
<tr id="row0">
<td id="id0" title="User ID Number">2</td>
<td id="email0" title="User Email">[email protected]</td>
<td id="forename0" title="User Forename">demo</td>
<td id="surname0" title="User Surname">doe</td>
<td>img</td>
</tr>
</tbody>
</div>
</table>
- 3 回答
- 0 關注
- 184 瀏覽
添加回答
舉報