js中Property和Attribute的区别是什么

JavaScript016

js中Property和Attribute的区别是什么,第1张

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>

property:属性;

method:方法;

1、属性直接与对象的某些方面(aspect)相关,或者更确切的说,是与对象表示的事物的某些方面相关。

属性很像变量:你只是通过它们的名字引用它们。

每个属性返回某种类型的一个值。访问属性的值不会改变对象或它所表示的任何事物的任何内容。

某些属性允许你为它们赋新值。这改变了对象的属性以及它表示的潜在内容。

2、方法是对象的程序所能为你做的事情。

方法很像函数和子例程;可以有参数传递给它们。

方法不必返回一个值,但是有些方法可以返回值。

调用方法可以修改对象或者它所表示的现实世界中的事物的某些内容。