首页 技术 正文
技术 2022年11月15日
0 收藏 657 点赞 2,992 浏览 1723 个字

说明:本文来自新浪博客,因为无法收藏,故直接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");
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,955
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774