jquery 书写全选反选功能

时间:2023-03-09 00:19:43
jquery 书写全选反选功能

书写一个后台管理中用到的全选反选功能。代码如下

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全选反选插件</title>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row6">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:250px;">
<button type="button" class="btn btn-success" id="check_all">全选</button>
<button type="button" class="btn btn-danger" id="check_others">反选</button>
</th>
<th>ID</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="son_checkbox" ></td>
<td>1</td>
<td>张三</td>
</tr>
<tr>
<td><input type="checkbox" class="son_checkbox" ></td>
<td>2</td>
<td>李四</td>
</tr>
<tr>
<td><input type="checkbox" class="son_checkbox" ></td>
<td>3</td>
<td>王五</td>
</tr>
<tr>
<td><input type="checkbox" class="son_checkbox" ></td>
<td>4</td>
<td>赵六</td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
$(function(){
//点击全选事件
$("#check_all").click(function(){
var text=$(this).text();
var status;
if(text=="全选")
{
status=true;
text="取消全选";
}
else if(text=="取消全选")
{
status=false;
text="全选";
}else
{
return false;
}
$(".son_checkbox").prop("checked",status);//改变状态
$(this).text(text);//设置文字
});
//点击反选事件
$("#check_others").click(function(){
//遍历所有选择框 然后反转状态
$(".son_checkbox").each(function(){
var now_status=$(this).prop("checked");//获取当前选择框是否选中
now_status=!now_status;//反转状态
$(this).prop("checked",now_status);//重新绑定状态
});
});
});
</script>
</body>
</html>

效果图如下:

jquery 书写全选反选功能