静默的温柔
短路工程师/目前财产:0只狗

今天饶有兴趣,探究一下单/复选框是如何判断被选中的。在以前(学校)的时候,判断方法是判断它的属性值.attr("checked")=="checked".如下代码所示:

if($(this).attr("checked")=="checked")

 

今天要告诉大家另外一种方法。第二种方法是使用了JQuery的方法prop().这个方法的作用是:获取或者设置匹配元素的属性值。例如可以使用这个方法设置元素的id,$("selecter").prop({id:XXX}),

获取元素的name,$("selecter").prop(name),以及其他的属性$("selecter").prop(attr);

所以想要获取单/复选框是否被选中,则需要获取$("selecter").prop("checked")即可。

两种方法达到效果一样,prop的用法是Jquery1.6添加的新方法,它有一些特性:

大家都知道有的浏览器只要写disabled,checked就可以了,而有的要写成disabled = "disabled",checked="checked",比如用attr("checked")获取checkbox的checked属性时选中的时 候可以取到值,值为"checked"但没选中获取值就是undefined。

jq提供新的方法“prop”来获取这些属性,就是来解决这个问题的,以前我们使用attr获取checked属性时返回"checked"和"",现在使用prop方法获取属性则统一返回true和false。

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

以下是官方建议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() )  

另外附上我的测试源代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=0.5,minimum-scale=0.5, maximum-scale=1.0, user-scalable=1" />
<script src="jquery-1.8.3.min.js" type="text/javascript"></script>    
<title>wqe</title>
</head>
<body>
    <div style="width:500px;margin:100px auto;">
        Genuis:<input type="radio" name="hello" value="genuis"><br>
        Sawadk:<input type="radio" name="hello" value="sawadk"><br>
        Vladimir:<input type="checkbox" name="vladimier" checked="checked" value="Vladimier"><br>
        Victor:<input type="checkbox" name="victor" value="Victor"><br>
        Reaper:<input type="checkbox" name="reaper" value="Reaper"><br>
        <span id="production"></span>
    </div>
</body>
<script>
    $("input").change(function(){
        var str="你选择了:";
        $("input").each(function()
        {
                if($(this).prop("checked"))
            {
                str+=$(this).val()+"    ";
                }
            })
            $("#production").text(str);
        }
        )
</script>
</html>     

还有运行效果截图:

posted on 2016-01-08 16:26  静默的温柔  阅读(1209)  评论(0编辑  收藏  举报