js中Property和Attribute的区别是什么

如题所述

DOM元素含有的这两个东西,虽然完全不是一回事,但却又紧密联系在一体,不细细体会,还真不好分清。Property-属性,就像C#等高级语言可以.(dot)获取或者设置其值;Attribute-特性,每一个dom元素都有一个attributes属性来存放所有的attribute节点,通过getAttribute()和setAttribute()方法来进行获取和操作。
1 <div id="test" name="div1" class="center" customtag="divTest"/>
上例中div里面的id、name、class还有自定义的customtag都放到了attributes里面,attributes类似数组的容器,名字索引存放的是name=value的attribute的节点,上面的就是
[class="center",name="div1",id="test",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="#" id="link">Test Link</a>
<img src="img.png" id="image" />
<input type="text" value="enter text" id="ipt" />
<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>
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-06-27
总结为attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。

attribute:attributes类似数组的容器,名字索引存放的是name=value的attribute的节点,要设置一个attribute节点使用setAttribute方法,要删除就用removeAttribute.attributes是会随着添加或删除attribute节点动态更新的.

property就是一个属性

很多attribute节点还有一个相对应的property属性,比如上面的div元素的id和class既是attribute,也有对应的property,不管使用哪种方法都可以访问和修改。