表格中当选中行控制复选框也能选中

来源:互联网 发布:淘宝卖 阿里进货 知乎 编辑:程序博客网 时间:2024/06/05 07:12

目的:行选择能触发复选框被选中

这是网上找到的一个例子

这个需求是在项目完成后客户提出的要求,看似简单但是还需要一点小手脚 Js代码  收藏代码$(".list tr").slice(1).each(function(){      var p = this;      $(this).children().slice(1).click(function(){          $($(p).children()[0]).children().each(function(){              if(this.type=="checkbox"){                  if(!this.checked){                      this.checked = true;                  }else{                      this.checked = false;                  }              }          });      });  });  只要table 的 class="list" ,就能实现该功能 $(".list tr").slice(1).each 意思是不要对表列头添加事件 $(this).children()..slice(1)是核心 主要为了过滤掉复选框所在的td的点击,否则在点复选框时将会起冲突

自己项目实际开发时候的采用的的

if($tr.children().first().children().is(':checked')){            $tr.children().first().children().prop("checked",false);            }else{            $tr.children().first().children().prop("checked",true);            }


在开发的时候出现了  点击效果有时候失效的现象,就是因为之前使用 。attr(“checked” false)方法,百度的时候发现是方法使用不当

1、$('obj').prop('checked',true)

2、$(':checkbox').each(function(){

    this.checked=true;

    })

为什么:attr为失效?因为checked属于为原型对象的属性。而attr在remove原型对象时会出错。原型对象指的是自身自带的,无法移除。prop会忽略这个错误。而attr操作的是普通非原型对象(可移除)。js 的dom对象属性是可以随意增加的。



阅读全文
0 0