首页 > 建站百科 > 公司新闻 > jquery获取checkbox 值为undefined

jquery获取checkbox 值为undefined

时间:2015-07-14 16:26:15 来源:西安网站建设
公司最近忙着开发网站内容管理系统,很多问题以前都没有仔细了解,当使用的时候才发现不少的小地方耽误了不少的时间,对此表示要好好学习啊。

做文章管理系统的时候,做一个很简单的文章排序,页面上实现全选/全不选这样一个简单的js,以前写代码的时候从来都是一次就搞定,不需要查看任何手册,但是这一次,莫名其妙的就是不能实现。每次使用jquery使用attr获取checkbox 值为都为undefined,着实郁闷了一下。代码是这样的


HTML:

<input type="checkbox" name="checkedAll" id="checkedAll" />

<input name="chk_list[]" type="checkbox" />
<input name="chk_list[]" type="checkbox" />
<input name="chk_list[]" type="checkbox" />
<input name="chk_list[]" type="checkbox" />
<input name="chk_list[]" type="checkbox" />

jQuery:

$("#checkedAll").click(function() {
     if ($(this).attr("checked") == true) {
         $("input[name='chk_list[]']").each(function() {
            $(this).attr("checked",true);
         });
      } else {
        $("input[name='chk_list[]']").each(function() {
            $(this).attr("checked",false);
         });
      }
});

使用alert弹出测试,每次使用jquery使用attr获取checkbox 值为都为undefined,然后查看jQuery API的文档,发现:

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.The difference between attributes and properties can be important in specific situations. 
Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

也就说:v1.6以后attr(‘checked’)就返回checked和undefined,v1.6以前返回true和false,v1.6以后可以使用is(‘:checked’)或者.prop(‘checked’)来返回true和false

总结:
(1)获取checked的方法

    .attr('checked'):  
    .prop('checked'): //1.6+:true/false
    .is(':checked'):   

(2)checked赋值

     所有的jquery版本都可以这样赋值:
     .attr("checked","checked");
     .attr("checked",true);

      jquery1.6以上版本的:
     .prop("checked",true);

    .prop("checked","checked");
    .prop({checked:true});
     .prop("checked",function(){
              return true;
      });

(3)note:jquery1.6以上才存在prop();

最后修改jQuery代码为:
 

$("#checkedAll").click(function() {
    if ($(this).prop("checked") == true) {
        $("input[name='chk_list[]']").each(function() {
           $(this).prop({checked:true});
        });
     } else {
        $("input[name='chk_list[]']").each(function() {
            $(this).prop({checked:false});
       });
    }
});

这样才成功。 再次记录一下, 以免以后再犯类似 的低级错误。