但我常遇到一個畫面有好幾個table
這樣每個都需要寫一次
這樣很麻煩程式碼也很長
<table>
<thead>
<tr class="active">
<th>
<label>
<input type="checkbox" class="selectAll" />全選</label>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" />
</td>
<tr>
<tr>
<td>
<input type="checkbox" />
</td>
<tr>
<tr>
<td>
<input type="checkbox" />
</td>
<tr>
<tr>
<td>
<input type="checkbox" />
</td>
<tr>
</tbody>
</table>
計畫是抓到這個checkbox的父table再向下抓closest這個語法可以查到指定的最上層
然後再用find向下找
程式依文字解讀就變下面
$('.selectAll').change(function () {
$(this).closest('table').find('tbody tr td input[type="checkbox"]').prop('checked', $(this).prop('checked'));
});
這樣只要checkbox class指定好不管多少table都能共用參考來源
.closest() | jQuery API Documentation