zoukankan      html  css  js  c++  java
  • jQuery.prop() 与attr()

    1.attr()jQuery 1.0版本就有的函数,prop()jQuery 1.6版本新增的函数。毫无疑问,在1.6之前,你只能使用attr()函数;1.6及以后版本,你可以根据实际需要选择对应的函数。

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

    3.在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)。

    4.selectedIndex,tagName,nodeName,nodeType,ownerDocument,defaultChecked,和defaultSelected应该被使用.prop()方法获取和设置。在jQuery1.6版本之前,这些properties是通过.attr()方法获取的,

    <div id="n1">
        <p id="n2" class="demo test" data-key="UUID" data_value="1235456465">CodePlayer</p>
        <input id="n3" name="order_id" type="checkbox" value="1">
        <input id="n4" name="order_id" type="checkbox" checked="checked" value="2">
    </div>

    var $n2 = $("#n2");

    // prop()操作针对的是元素(Element对象)的属性,而不是元素节点(HTML文档)的属性
    document.writeln( $n2.prop("data-key") ); // undefined
    document.writeln( $n2.prop("data_value") ); // undefined
     
    document.writeln( $n2.prop("id") ); // n2
    document.writeln( $n2.prop("tagName") ); // P
    document.writeln( $n2.prop("className") ); // demo test
    document.writeln( $n2.prop("innerHTML") ); // CodePlayer
    document.writeln( typeof $n2.prop("getAttribute") ); // function
     
    // 以对象形式同时设置多个属性,属性值可以是对象、数组等任意类型
    $n2.prop( {
      prop_b: "baike",
      prop_c: 18,
      site: { name: "CodePlayer", url: "http://www.jb51.net/" }
    } );
     
    -------------------------attr-----------------------------prop-----------------------------------
    w( $msg.attr("class") ); // test
    $msg.prop("className", "newTest");
    // 修改className(property)导致class(attitude)也随之更改
    w( $msg.attr("class") ); // newTest
  • 相关阅读:
    二十三、java连接oracle数据库操作:jdbc
    四、正则表达式使用
    Linux常用命令大全
    消息队列的常见问题
    JVM:带你查看常见的问题,以及分析处方法
    JVM监控与调优
    缓存总结2
    缓存总结1
    消息队列mq总结
    Java集合Map基本方法
  • 原文地址:https://www.cnblogs.com/wlhebut/p/7943045.html
Copyright © 2011-2022 走看看