码迷,mamicode.com
首页 > 其他好文 > 详细

attribute与property区别总结

时间:2015-01-15 23:42:09      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

在前阵子看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

技术分享

 

attribute与property区别总结

标签:

原文地址:http://www.cnblogs.com/qianlegeqian/p/4227487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!