jQuery函数attr()和prop()的区别

在jQuery中,prop()函数的设计目标是用于设置或获取指定DOM元素(指的是JS对象,Element类型)上的属性(property);attr()函数的设计目标是用于设置或获取指定DOM元素所对应的文档节点上的属性(attribute)。

当然,在jQuery的底层实现中,函数attr()prop()的功能都是通过JS原生的Element对象(document.getElementById("ID"))实现的。attr()函数主要依赖的是Element对象的getAttribute()setAttribute()两个方法。prop()函数主要依赖的则是JS中原生的对象属性获取和设置方式。

------------------------------↓   划重点   ↓-----------------------------

在jQuery 1.6之前,只有attr()函数可用,该函数不仅承担了attribute的设置和获取工作,还同时承担了property的设置和获取工作。例如:在jQuery 1.6之前,attr()也可以设置或获取tagName、className、nodeName、nodeType等DOM元素的property。

直到jQuery 1.6新增prop()函数,并用来承担property的设置或获取工作之后,attr()才只用来负责attribute的设置和获取工作。

此外,对于表单元素的checkedselecteddisabled等属性,在jQuery 1.6之前,attr()获取这些属性的返回值为Boolean类型:如果被选中(或禁用)就返回true,否则返回false

但是从1.6开始,使用attr()获取这些属性的返回值为String类型,如果被选中(或禁用)就返回checkedselecteddisabled,否则(即元素节点没有该属性)返回undefined。并且,在某些版本中,这些属性值表示文档加载时的初始状态值,即使之后更改了这些元素的选中(或禁用)状态,对应的属性值也不会发生改变。

因为jQuery认为:attribute的checkedselecteddisabled就是表示该属性初始状态的值,property的checkedselecteddisabled才表示该属性实时状态的值(值为truefalse)。

因此,在jQuery 1.6及以后版本中,请使用prop()函数来设置或获取checkedselecteddisabled等属性。对于其它能够用prop()实现的操作,也尽量使用prop()函数。

 

    <div id="yearDiv" style="float: left">
                    <input type="checkbox" id="2016" checked="checked" style="width:20px;vertical-align: middle;" onclick="selectchanged();" />
                    <label for="2016" style="font-size: 13px; ">2016</label>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <input type="checkbox" id="2015" checked="checked" style="width:20px;vertical-align: middle;" onclick="selectchanged();" />
                    <label for="2015" style="font-size: 13px; ">2015</label>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <input type="checkbox" id="2014" style="width:20px;vertical-align: middle;" onclick="selectchanged();" />
                    <label for="2014" style="font-size: 13px; ">2014</label>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <input type="checkbox" id="2013" style="width:20px;vertical-align: middle;" onclick="selectchanged();" />
                    <label for="2013" style="font-size: 13px; ">2013</label>
                    <span>&nbsp;&nbsp;&nbsp;&nbsp;</span>
            
        </div>

全选中的js方法:

function AllSelect() {
    $("#yearDiv input[type='checkbox']").each(function () {
         $(this).prop("checked", true);
    });
};

 

posted on 2017-09-20 10:22  風云  阅读(256)  评论(0编辑  收藏  举报

导航