$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

时间:2023-03-09 02:38:52
$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

<input type='checkbox' id='cb'/> 
<script> 
//获取是否选中 
var isChecked = $('#cb').attr('checked'); 
//设置选中 
$('#cb').attr('checked',true); 
</script> 
这样写在Jquery1.6之前完全没问题,可是当我们升级1.6到更高的版本时,问题就来了,此时我们会发现: 
$('#cb').attr('checked'); 返回的是chec
<input type='checkbox' id='cb'/> 
<script> 
//获取是否选中 
var isChecked = $('#cb').attr('checked'); 
//设置选中 
$('#cb').attr('checked',true); 
</script> 
这样写在Jquery1.6之前完全没问题,可是当我们升级1.6到更高的版本时,问题就来了,此时我们会发现: 
$('#cb').attr('checked'); 返回的是checked或者是undefined,不是原来的true和false了。 并且checked属性在页面初始化的时候已经初始化好了,不会随着状态的改变而改变。所以如果checkbox一开始是选中的,那么返回的是checked,如果一开始没被选中,则返回的是undefined
<input type='checkbox' id='cb'/> 
<script> 
//获取是否选中 
var isChecked = $('#cb').prop('checked'); 
//或 
var isChecked = $('#cb').is(":checked"); 
//设置选中 
$('#cb').prop('checked',true); 
</script> 
原因是:
它将“属性”与“特性”做了区别,属性指的是“name,id”等等,特性指的是“selectedIndex, tagName, nodeName”等等。 
Jquery1.6之后,可以通过attr方法去获得属性,通过prop方法去获得特性
$("#cb").attr("tagName"); //undefined 
$("#cb").prop("tagName"); //INPUT 

那么,什么时候使用attr(),什么时候使用prop()?
1.添加属性名称该属性就会生效应该使用prop();
2.是有true,false两个属性使用prop();
3.其他则使用attr();
项目中jquery升级的时候大家要注意这点!

以下是官方建议attr(),prop()的使用:

分析了其中的原因,可以这样理解: 
它将“属性”与“特性”做了区别,属性指的是“name,id”等等,特性指的是“selectedIndex, tagName, nodeName”等等。 
JQ1.6之后,可以通过attr方法去获得属性,通过prop方法去获得特性

Attribute/Property .attr() .prop()
accesskey  
align  
async
autofocus
checked
class  
contenteditable  
draggable  
href  
id  
label  
location ( i.e. window.location )
multiple
readOnly
rel  
selected
src  
tabindex  
title  
type  
width ( if needed over .width() )

按照下面為標準

最近在iteye的新闻中看到jQuery已经更新到了1.6.1。和之前版本的最大变化是增加了.prop方法。但是.prop()方法和.attr()方法,单从字面上很难区分。在汉语中properties和attributes都有表示“属性”的意思。
下面根据这篇博文(javascript:mctmp(0);),简要翻译了.prop()和.attr()的用法:

1、从1.5.2升级到1.6.1

通过介绍新方法.prop()以及.attr()方法的改变,jQuery1.6.1引起了一场关于attributes和properties之间有何区别和联系的激烈讨论。同时,1.6.1也解决了一些向后兼容性问题。当从1.5.2升级到1.6.1时,你不必修改任何attribute代码。

下面是关于jQuery1.6和1.6.1中Attributes模块变化的描述,以及.attr()方法和.prop()方法的首选使用。然而,正如前面所述,jQuery1.6.1允许你使用.attr()方法就像以前它被使用在所有的情况中一样。

2、发生了什么变化

Attributes模块的变化是移除了attributes和properties之间模棱两可的东西,但是在jQuery社区中引起了一些混乱,因为在1.6之前的所有版本中都使用一个方法(.attr())来处理attributes和properties。但是老的.attr()方法有一些bug,很难维护。jQuery1.6.1对Attributes模块进行了更新,并且修复了几个bug。

特别提到的是,boolean attributes,比如:checked,selected,readonly和disabled在1.6.1中和1.6之前的处理相同。这意味着下面的代码:

$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

  1. $(“:checkbox”).attr(“checked”, true);
  2. $(“option”).attr(“selected”, true);
  3. $(“input”).attr(“readonly”, true);
  4. $(“input”).attr(“disabled”, true);
$(“:checkbox”).attr(“checked”, true);
$(“option”).attr(“selected”, true);
$(“input”).attr(“readonly”, true);
$(“input”).attr(“disabled”, true);

甚至是这样的代码:$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

  1. if ( $(“:checkbox”).attr(“checked”) ) { /* Do something */ }
if ( $(“:checkbox”).attr(“checked”) ) { /* Do something */ }

在1.6.1中没有必要为了保持之前期望的运行结果而发生任何改变。

为了让jQuery1.6中的.attr()方法的变化被理解的清楚些,下面是一些使用.attr()的例子,虽然在jQuery之前的版本中能正常工作,但是现在必须使用.prop()方法代替:

$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

首先,window或document中使用.attr()方法在jQuery1.6中不能正常运行,因为window和document中不能有attributes。它们包含properties(比如:location或readyState),必须使用.prop()方法操作或简单地使用javascript原生的方法。在jQuery1.6.1中,window和document中使用.attr()将被自动转成使用.prop,而不是抛出一个错误。

其次,checked,selected和前面提到的其它boolean attributes,因为这些attributes和其相应的properties之间的特殊关系而被特殊对待。基本上,一个attribute就是以下html中你看到的:$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

  1. <input type=”checkbox” checked=”checked”>
<input type=”checkbox” checked=”checked”>

boolean attributes,比如:checked,仅被设置成默认值或初始值。在一个checkbox的元素中,checked attributes在页面加载的时候就被设置,而不管checkbox元素是否被选中。

properties就是浏览器用来记录当前值的东西。正常情况下,properties反映它们相应的attributes(如果存在的话)。但这并不是boolean attriubutes的情况。当用户点击一个checkbox元素或选中一个select元素的一个option时,boolean properties保持最新。但相应的boolean attributes是不一样的,正如上面所述,它们仅被浏览器用来保存初始值。$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

  1. $(“:checkbox”).get(0).checked = true;
  2. // Is the same as $(":checkbox:first").prop(“checked”, true);
$(“:checkbox”).get(0).checked = true;
// Is the same as $(":checkbox:first").prop(“checked”, true);

在jQuery1.6中,如果使用下面的方法设置checked:

$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

  1. $(“:checkbox”).attr(“checked”, true);
$(“:checkbox”).attr(“checked”, true);

将不会检查checkbox元素,因为它是需要被设置的property,但是你所有的设置都是初始值。

然而,曾经jQuery1.6被释放出来的时候,jQuery团队明白当浏览器仅关心页面加载时,设置一些值不是特别的有用。所以,为了保持向后兼容性和.attr()方法的有用性,我们可以继续在jQuery1.6.1中使用.attr()方法取得和设置这些boolean attributes。

最普通的attributes是checked,selected,disabled和readOnly,但下面是jQuery1.6.1支持的使用.attr()动态地取得和设置boolean attributes/properties的完整列表:$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

  1. autofocus, autoplay, async, checked, controls, defer, disabled,
  2. hidden, loop, multiple, open, readonly, required, scoped, selected
autofocus, autoplay, async, checked, controls, defer, disabled,
hidden, loop, multiple, open, readonly, required, scoped, selected

(译者注:大部分都是html5新增的属性)

还是建议使用.prop()方法来设置这些boolean attributes/properties,即使这些用例没有转换成使用.prop()方法,但是你的代码仍然可以在jQuery1.6.1中正常运行。

下面是一些attributes和properties的列表,正常情况下,应该使用其对应的方法(见下面的列表)来取得和设置它们。下面的是首用法,但是.attr()方法可以运行在所有的attributes情况下。

注意:一些DOM元素的properties也被列在下面,但是仅运行在新的.prop()方法中

$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法

*例如: window.location
**如果需要在(if needed over) .width()

.attr()和.prop()都不应该被用来取值/设值。使用.val()方法代替(即使使用.attr("value","somevalue") 可以继续运行,就像1.6之前做的那样)

3、首选用法的概述

.prop()方法应该被用来处理boolean attributes/properties以及在html(比如:window.location)中不存在的properties。其他所有的attributes(在html中你看到的那些)可以而且应该继续使用.attr()方法来进行操作。

上面的概述已经描述的够清楚了,我也没有必要再总结了。

另一個

<input id="cb2" type="checkbox" checked="checked" />

--------------------------------------------------------------

jquery判断checked的三种方法:

.attr('checked'):   //看版本1.5-返回:true或false
.prop('checked'): //16+:true/false
.is(':checked'):    //所有版本:true/false//别忘记冒号哦

jquery赋值checked的几种写法:

// $("#cb1").prop("checked",function(){
return true;//函数返回true或false
});

//记得还有这种哦:$("#cb1").prop("checked","checked");

更多参考:http://api.jquery.com/prop/

上代码 大家可以随便测试:(你是懒人么-_-)

jquery1.6以后才支持prop的哦

新建一个text复制内容进去  后缀名改成html

$('#checkbox').attr('checked'); 返回的是checked或者是undefined解决办法
<html>

<head>

<title>测试</title>

<style type="text/css"> </style>

<!--1.62可以修改1.42 1.52 1.7来测试-->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

<script type="text/javascript">

$(function(){

//判断checked

       // var a=$("#cb1").attr('checked'); //看版本1.6+返回:"checked"或"undefined" ;1.5-返回:true或false

       // var b=$("#cb1").prop('checked'); //1.6+:true/false

       var c=$("#cb1").is(':checked'); //所有版本:true/false

       // alert(a);

       // alert(b);

alert(c); //赋值 前两个所有的jquery版本都支持 prop只有jquery1.6+支持

       // $("#cb1").attr("checked","checked");//1.5-

       // $("#cb1").attr("checked",true);//1.5-
       //   $("#cb1").prop("checked","checked");//1.6+(整理的时候把这个忘记啦)
       //    $("#cb1").prop("checked",true);//1.6+

       // $("#cb1").prop({checked:true});//1.6+

      // $("#cb1").prop("checked",function(){

       // return true;//1.6+

       // });

})(); </script>

</head>

<body>

<!--赋值的时候记得去掉checked-->

<input id="cb1" type="checkbox" checked />

<input id="cb2" type="checkbox" checked="checked"/>

</body>

</html>

以上內容全部為轉載

随机推荐

  1. 【leetcode❤python】24. Swap Nodes in Pairs

    #-*- coding: UTF-8 -*- # Definition for singly-linked list.# class ListNode(object):#     def __init ...

  2. HDU 5013 City Tour

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5013 题意: 思路: 这里有错,是Hi(x)=sigama(Hji)(j属于x) const int ...

  3. vim使用札记

    最近开始用vim编辑器了,从最开始的配置到现在慢慢使用,我在这儿会贴出一些我的使用上遇到过的问题和如何解决的方案,留给自己和一些会用到的人看看 1.vim怎么使汇编语法高亮 开始不知道,然后把文件的后 ...

  4. [SAP ABAP开发技术总结]EXIT-COMMAND

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  5. JQ将数组转换为Json

    var ArrComList; try { //接口传进来的数据格式为 A,B,C,D,这里根据逗号分隔返回数组. ArrComList = WeighControl.GetComList().spl ...

  6. HDU1518 Square(DFS)

    Square Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Su ...

  7. elcipse 中利用maven创建web工程

    如何创建: http://huxiaoheihei.iteye.com/blog/1766986 遇到的问题: 1: 如果spring MVC配置了 <servlet> <servl ...

  8. Doragon Kuesuto 1.6

    /* * <<D Q>> * * Author xkfx<wyzxk_fx@163.com> * * 游戏规则:利用适当的决策,在13回合内击杀恶龙取得胜利. * ...

  9. typeof升级版,可以识别出array、object、null、nan、[]、{}

    typeof 经常混淆array.object.null等,升级处理一下. 可以将这个函数放在common.js中使用. function getTypeName(v) { var v_str = J ...

  10. ORA-32004 参数设置过时的解决办法

    启动时报错: 查看日志: view /opt/oracle11g/app/db/diag/rdbms/yldev/yldev/trace/alert_yldev.log 原来是plsql_debug ...