jQuery实现全选和反选-奥妙大揭秘

来源:互联网 发布:视频音频剪辑软件 编辑:程序博客网 时间:2024/06/06 10:04

技术如果没有经过实践,恐难体会其中奥妙,这么一个简单功能亦是如此!

Html代码:

<div>    <input id="checkAll" type="checkbox" />全选    <input name="subBox" type="checkbox" />项1    <input name="subBox" type="checkbox" />项2    <input name="subBox" type="checkbox" />项3    <input name="subBox" type="checkbox" />项4    </div>

第一个版本,个人认为已经是目前网上能看到的相同需求最精简的代码,两个函数搞定:

$(function() {       $("#checkAll").click(function() {            $('input[name="subBox"]').attr("checked",this.checked);         });        var $subBox = $("input[name='subBox']");        $subBox.click(function(){            $("#checkAll").attr("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false);        });    });

但是这个版本在jQuery 1.6+不好使,如果使用1.6+,那么应该将attr改成prop:

$(function () {    $("#checkAll").click(function () {        $('input[name="subBox"]').prop("checked", this.checked);    });    var $subBox = $('input[name="subBox"]');    $subBox.click(function () {        $("#checkAll").prop("checked", $subBox.length == $("input[name='subBox']:checked").length ? true : false);    });});

分析

需求再简单不过,足足花了两个小时。直到使用浏览器调试工具,发现checkbox中确实有checked属性,但是页面中checkbox并没有变成选中状态。

我是不会放过去分析、深挖的!

什么是attributes?什么是properties?

ttributes和properties之间的差异在特定情况下是很重要。jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值时,会返回 property 的值,这就导致了结果的不一致。从 jQuery 1.6 开始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值。

例如, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected 应使用.prop()方法进行取值或赋值。 在jQuery1.6之前,这些属性使用.attr()方法取得,但是这并不是元素的attr属性。他们没有相应的属性(attributes),只有特性(property)。

例如,考虑一个DOM元素的HTML标记中定义的<input type="checkbox" checked="checked" /> ,并假设它是一个JavaScript变量命名的elem:

elem.checked true (Boolean) 将改变复选框的状态
$(elem).prop(“checked”) true (Boolean) 将改变复选框的状态
elem.getAttribute(“checked”) “checked” (String) 不会改变的复选框的初始状态;
$(elem).attr(“checked”) (1.6) “checked” (String) 不会改变的复选框的初始状态;
$(elem).attr(“checked”) (1.6.1+) “checked” (String) 将改变复选框的状态
$(elem).attr(“checked”) (pre-1.6) true (Boolean) 将改变复选框的状态

为了方便再来针对CheckBox选中操作小结下:

  • jquery判断checked的三种方法:

    • .attr(‘checked)://看版本1.6+返回:”checked”或”undefined” ;1.5-返回:true或false
    • .prop(‘checked’)://16+:true/false
    • .is(‘:checked’): //所有版本:true/false//别忘记冒号哦
  • jquery赋值checked的几种写法:

    • 所有的jquery版本都可以这样赋值:

      $(“#cb1”).attr(“checked”,”checked”);
      $(“#cb1”).attr(“checked”,true);

    • jquery1.6+:prop的4种赋值:

      $(“#cb1″).prop(“checked”,true);
      $(“#cb1″).prop({checked:true}); //map键值对
      $(“#cb1″).prop(“checked”,function(){
      return true;//函数返回true或false
      });
      $(“#cb1″).prop(“checked”,”checked”);

0 0
原创粉丝点击