zoukankan      html  css  js  c++  java
  • attribute与property区别总结

    在前阵子看JQuery源码中,attr()的简单理解是调用了element.getAttribute()和element.setAttribute()方法,removeAttr()简单而言是调用element.removeAttribute(),而prop()简单理解是element.xxx方式存取属性,removeProp()是通过delete element.xxx方式删除。

    attribute与property都是属性的意思。那么有何区别呢?

    对于这个问题,今天问了好几个群,也找到一些文章(感谢他们~~)

    主要是看了下面几篇:

    http://gxxsite.com/content/view/id/135.html

    http://nuysoft.iteye.com/blog/1172122

    http://www.tuicool.com/articles/3uuQRr6

    http://www.web-tinker.com/article/20115.html

    http://www.cnblogs.com/aaronjs/p/3387906.html

    http://www.w3help.org/zh-cn/causes/SD9006

    总结如下

    attribute  property 举例
    HTML属性 DOM节点对象属性  
    返回初始化的值 返回当前的值
    //<input id="test" type="text"/>
    var test=document.getElementById("test");
    test.getAttribute("required")
    //null
    test.required
    //false

    比如获取当前文本框的value

    返回字符串 可以返回多种格式,可以是字符串,也可以是对象
     //<input id="test" type="text" style="color:#666"/>
    
    var test=document.getElementById("test"); test.style
     
    //CSSStyleDeclaration {0: "color", parentRule: null, length: 1, 
    cssText: "color: rgb(102, 102, 102);", alignContent: "", alignItems: ""…}
    test.getAttribute("style")
    //"color:#666"
    返回值与HTML代码中的属性值相同 返回值与HTML代码中的属性值可能不同
    //<a id="test" href="/aaa.html">aaaaa</a>
    var test=document.getElementById("test");
    test.getAttribute("href")
    //"/aaa.html"
    test.href
    //"file:///C:/aaa.html"
    还比如checked属性
     可以获取HTML代码中自定义的属性  只能获取原生的属性值
    //<input id="test" type="text" custom="text"/>
    
    var test=document.getElementById("test");
    
    test.getAttribute("custom")
    //"text"
    test.custom
    //undefined
    设值时DOM树结构变了 设值时DOM树结构不变
    //<input id="test" type="text" value="10"/>
    var test=document.getElementById("test"); test.value=20;
    //<input id="test" type="text" value="10">
    test.setAttribute("value",20)
    //<input id="test" type="text" value="20">
         

    其他:

    1、element.className与 element.getAttribute("class") 

    2、element.for (获取不到)与 element.getAttribute("for") 

    3、element.onclick 与 element.getAttribute("onclick") (获取不到)
    4、element.nodeName 

    5、属性值在浏览器之间的差异,举例:

    //<input id="test" type="checkbox" checked="checked" />
    
    alert(document.getElementById("test").checked);
    //true(Chrome)
    //true(IE7)
    
    alert(document.getElementById("test").getAttribute("checked"));
    //checked(Chrome)  
    //true(IE7)

    6、关于jq

    ①性能:prop>data>attr

  • 相关阅读:
    团队会议第八天
    团队会议第七天
    站立会议第五天
    站立会议第四天
    站立会议第三天
    站立会议第二天
    站立会议第一天(2016.4.19)
    团队报告
    团队计划backlog
    每日Scrum(5)
  • 原文地址:https://www.cnblogs.com/qianlegeqian/p/4227487.html
Copyright © 2011-2022 走看看