Javascript中Property和Attribute的区别

DOM元素含有的这两个东西,虽然完全不是一回事,但却又紧密联系在一体,不细细体会,还真不好分清。Property-属性,就像C#等高级语言可以.(dot)获取或者设置其值;Attribute-特性,每一个dom元素都有一个attributes属性来存放所有的attribute节点,通过getAttribute()和setAttribute()方法来进行获取和操作。

1 <div  name="div1" class="center" customtag="divTest"/>

上例中div里面的id、name、class还有自定义的customtag都放到了attributes里面,attributes类似数组的容器,名字索引存放的是name=value的attribute的节点,上面的就是

[class="center",name="div1",,customtag="divTest"]

需要获取和设置这些attribute,很简单

document.getElemmentById("test").getAttribute("customtag") //divTest
document.getElemmentById("test").setAttribute("data","11")
document.getElemmentById("test").removeAttribute("data")

Property就是一个属性,如果把DOM元素看成是一个普通的object对象,那么property就是以name=value形式存放在Object中的属性(C#中的类似),操作很简单

elem.gameid = 880; // 添加
    console.log( elem.gameid ) // 获取

这两个东西有什么联系和区别呢?

首先,很多attribute节点有一个相应的property属性,如例子中的div元素的id和class既是attribute也有property,不管哪种方式都可以访问和修改,但是对于自定义的attribute节点,或者自定义property,两者就没有关系了,对于IE6-7来说,没有区分attribute和property。具体的讲解可以考attribute和property的区别,很详细。

虽然getAttribute和点号方法都能获取标准属性,但是他们对于某些属性,获取到的值存在差异性,比如href,src,value等

<a href="#" >Test Link</a>
<img src="img.png"  />
<input type="text" value="enter text"  />
<script>
var $ = function(id){return document.getElementById(id);};
alert($('link').getAttribute('href'));//#
alert($('link').href);//fullpath/file.html#

alert($('image').getAttribute('src'))//img.png
alert($('image').src)//fullpath/img.png

alert($('ipt').getAttribute('value'))//enter text
alert($('ipt').value)//enter text
$('ipt').value = 5;
alert($('ipt').getAttribute('value'))//enter text
alert($('ipt').value)//5
</script>

一些讲解的比较详细的文章,我做了下整理,有需要的朋友可以继续看一下

http://stylechen.com/attribute-property.html

http://javascript.info/tutorial/attributes-and-custom-properties

http://omiga.org/blog/archives/2055