JS中attribute和property的区别

JavaScript013

JS中attribute和property的区别,第1张

property是DOM中的属性,是JavaScript里的对象;

attribute是HTML标签上的特性,它的值只能够是字符串;

简单理解,Attribute就是dom节点自带的属性,例如html中常用的id、class、title、align等。

而Property是这个DOM元素作为对象,其附加的内容,例如childNodes、firstChild等。

常用的Attribute,例如id、class、title等,已经被作为Property附加到DOM对象上,可以和Property一样取值和赋值。但是自定义的Attribute,就不会有这样的特殊优待。

就是说Dom对象上也有id,className(class是关键字,所以用了className),一部分属性都有。

结论:

attribute 是property的子集, 所有改动attribute ,property 也会改变,反之不行

property能够从attribute中得到同步;

attribute不会同步property上的值;

attribute和property之间的数据绑定是单向的,attribute->property;

更改property和attribute上的任意值,都会将更新反映到HTML页面中;

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、Attribute:是获取属性的值$("obj").attribute("id"),或设置属性$("obj").attribute("id",1)是一个方法。

2、prototype:prototype 属性使您有能力向对象添加属性和方法。 语法 object.prototype.name=value实例