JavaScript中的Attribute和Property區別

<div id="test" name="div1" class="center" customtag="divTest"/>html

上例中div裏面的id、name、class還有自定義的customtag都放到了attributes裏面,attributes相似數組的容器,名字索引存放的是name=value的attribute的節點數組


document.getElemmentById("test").getAttribute("customtag") //divTestspa


不少attribute節點有一個相應的property屬性,如例子中的div元素的id和class既是attribute也有property,無論哪一種方式均可以訪問和修改,可是對於自定義的attribute節點,或者自定義property,二者就沒有關係了,對於IE6-7來講,沒有區分attribute和property。htm


雖然getAttribute和點號方法都能獲取標準屬性,可是他們對於某些屬性,獲取到的值存在差別性,好比href,src,value等索引

<a href="#" id="link">Test Link</a>ip

<img src="img.png" id="image" />get

<input type="text" value="enter text" id="ipt" />input

<script>io

var $ = function(id){return document.getElementById(id);};function

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

相關文章
相關標籤/搜索