jq表格反选功能代码实实现
时间: 2024-01-07 18:06:05 浏览: 31
表格反选功能是指当用户点击“反选”按钮时,会将表格中未选中的行变为选中状态,已选中的行变为未选中状态。下面是一个使用 jQuery 实现表格反选功能的示例代码:
HTML代码:
```html
<table id="myTable">
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></th>
<th>Name</th>
<th>Age</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="select"></td>
<td>John</td>
<td>30</td>
<td>USA</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>Jane</td>
<td>25</td>
<td>Canada</td>
</tr>
<tr>
<td><input type="checkbox" name="select"></td>
<td>Tom</td>
<td>40</td>
<td>UK</td>
</tr>
</tbody>
</table>
<button id="invert">Invert Selection</button>
```
JavaScript代码:
```javascript
$(function() {
// 全选/全不选
$("#checkAll").click(function() {
$("input[name='select']").prop("checked", $(this).prop("checked"));
});
// 反选
$("#invert").click(function() {
$("input[name='select']").each(function() {
$(this).prop("checked", !$(this).prop("checked"));
});
});
});
```
这段代码先给全选复选框 `#checkAll` 绑定了一个点击事件,当点击全选复选框时,会将所有的行复选框的选中状态与全选复选框的选中状态同步。然后给“反选”按钮 `#invert` 绑定了一个点击事件,当点击“反选”按钮时,会遍历所有的行复选框,将它们的选中状态取反。这样就实现了表格反选功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)