您的位置:首页 > Web前端 > JQuery

jquery解决单选和全选问题

2020-03-29 12:59 836 查看

业务:点击全选,单选全选择,反之单选全选全选也会改变状态,如果不满足那全选择不改变状态

<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<thead>
<tr>
<th><input type="checkbox" id="checkAll">全选</th>
<th>用户名</th>
<th>操作</th>
<th>请求方法</th>
<th>请求参数</th>
<th>IP</th>
<th>执行时长</th>
</tr>
</thead>
<tbody id="tbodyId">
<tr>
<td colspan="7">数据正在加载中...</td>
</tr>
</tbody>
</table>
</div>
$(function(){
$("#pageId").load("doPageUI",doGetObjects);
//在input-group-btn容器对象上注册点击事件
$(".input-group-btn")
.on("click",".btn-search",doQueryObjects)
.on("click",".btn-delete",doDeleteObjects);
//全选按钮事件注册
$("#checkAll").change(doChangeTBodyCheckBoxState);
//tbody中checkbox对象事件注册
$("#tbodyId")
.on("change",".cBox",doChangeTHeadCheckBoxState)
});
//修改tHead中checkbox对象的状态
function doChangeTHeadCheckBoxState(){
//1.定义状态初始值.
var flag=true;
//2.迭代tbody中所有checkbox对象,并将其
//对象的状态值与flag变量进行逻辑与操作.
$("#tbodyId input[type='checkbox']")
.each(function(){
flag=flag&&$(this).prop("checked");
})
//3.修改thead中checkbox对象状态
$("#checkAll").prop("checked",flag);
}

//修改tbody中checkbox对象的状态
function doChangeTBodyCheckBoxState(){
//1.获得全选对象的状态值
var flag=$(this).prop("checked");//2.修改tbody中checkbox对象状态
$("#tbodyId input[type='checkbox']")
.prop("checked",flag);
}

checkboxAll和cBox是需要改变的对象
思路是:全选 — 获取全选checkbox的状态所谓的checked,根据官网资料得知input框 type=“checkbox” 如果有checked属性就会被默认选中
所以,先获取全选的check,获得将单选全部加上check属性,

var flag=$(this).prop("checked");
  1. 在这个情况下要么check有得true,那么单选获得 $("#checkAll").prop(“checked”,true);
  2. 全选没有check属性得false,那么单选不定位会被改变 $("#checkAll").prop(“checked”,false);
    单选 — 定位单选,遍历每个是否有check属性,倘若一个没有就为false,全都有将为true
$("#tbodyId input[type='checkbox']")
.each(function(){
flag=flag&&$(this).prop("checked");
})
//3.修改thead中checkbox对象状态  flag为true或false
$("#checkAll").prop("checked",flag);

另外根据attr实现

$("th input[type='checkbox']").on("click",function(){
  if($(this).attr("checked")==("checked"){//点击全选复选框 全选所有商品
    var $selectAll = $("tr td input[type='checkbox']");
    //alert($selectAll.length);
    $selectAll.each(function(){
    $(this).attr("checked","checked");
  });
}else{//点击全选复选框 取消全选所有商品
  var $selectAll = $("tr td input[type='checkbox']");
  //alert($selectAll.length);
 $selectAll.each(function(){
  $(this).attr("checked",false);
 });
}
});
  • 点赞
  • 收藏
  • 分享
  • 文章举报
qq_44801336 发布了54 篇原创文章 · 获赞 5 · 访问量 730 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: