zoukankan      html  css  js  c++  java
  • Jquery获取checkbox属性checked为undefined

    说明:本文来自新浪博客,因为无法收藏,故直接copy过来备注,以后好查询

    原网址:http://blog.sina.com.cn/s/blog_6810dfc20101jddq.html

    使用jQuery v1.10.2获取checkbox的状态时,用.attr("checked")时输出总是为undefined.郁闷了,这难道是个bug?!

    查看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();

    checkbox操作:

    <input id="cbxAll" type="checkbox" title="全选" name="cbxAll" onclick="CheckAll()" />
    <input id="cbx1" type="checkbox" title="单选" name="cbxType" onclick="CheckOne()"/>
    function CheckAll() {
        var checkall = $("#cbxAll").prop("checked");
        if (checkall) {
        //全选 $(
    "input:checkbox[name='cbxType']").prop("checked", true); } else {
        //取消全选 $(
    "input:checkbox[name='cbxType']").prop("checked", false); } }
    function CheckOne() {
      $("#cbxAll").prop("checked",false);
    }
    var checkedboxes = $("input:checkbox[name='cbxType']:checked");
  • 相关阅读:
    调研一类软件的发展演变—聊天软件( 1000-2000 words, in Chinese)
    C++用法的学习心得(要求包含示例,并反映出利用网络获取帮助的过程)
    软件工程学习总结
    南通大学教务管理微信公众号体验
    设计一款给爸爸妈妈用的手机
    第二次作业
    web browser 发展史
    c++用法的学习心得
    电梯调度
    一个数组既有正数也有负数,计算出它的子数组和的最大值。
  • 原文地址:https://www.cnblogs.com/zhyue93/p/checkbox.html
Copyright © 2011-2022 走看看