DOM中Property與Attribute的區別

#DOM中Property與Attribute的區別javascript

property和attribute的漢語翻譯幾乎相同,都有「屬性」的意義(這裏姑且稱attribute爲「特性」,以方便區分),而他們的取值也常常相同,但有時又會踩坑,發現兩者會不相等,不一樣步。如下文章總結一下它倆的特性和區別。更詳情的對比,請看參考文章:DOM中Property與Attribute的區別java

##簡述web

Property就是這些,至關於jQuery.prop():dom

dom.checked = false;
dom.id = "footer";
$dom.prop("checked", false)

attribute就是這些,至關於jQuery.attr():spa

dom.setAttribute("href", "/download/");
dom.getAttribute("id");
$dom.attr("href", "/download/")

##差別翻譯

  1. prop經過點.讀寫dom的屬性;attr經過setAttribute和getAttribute方法
  2. prop大小寫敏感;attr則不敏感
  3. prop原則上讀寫屬性不出如今HTML中,除了id,src,href等,attr則都會影響到HTML

##同步與不一樣步code

  1. 自定義的prop,與attr不一樣步,也不相等
  2. 非自定義的prop與attr是有條件同步的,即有的時候寫入prop會同步到attr,有的時候寫入attr會同步到prop。詳情可看參考文章

##其餘ip

  1. 萬惡之源IE,版本9如下的property與attribute是徹底相同的,除了class(className = class)
  2. attr讀寫屬性中,傳入的屬性名不能包含空格,不然會報錯,如:dom.setAttribute("a space", 100);
  3. 對於href屬性,prop與attr同步而不一樣值,如
// 對於<a href="/test/">link</a>
a.getAttribute("href")// => /test/
a.href // => http://www.example.com/test/
  1. 而對於checked屬性,prop設置爲false會生效,而attr設爲"false"則沒用,需把"checked"的屬性刪掉
相關文章
相關標籤/搜索