JavaScript の 內容屬性(HTML屬性attribute)和 DOM 屬性(property)

[博文]內容屬性(HTML屬性)和 DOM 屬性

標籤: 博文 JavaScript瀏覽器



粗略解讀(與jQuery作對比)

  • 內容屬性(HTML屬性) : attributedom

  • DOM 屬性(Element屬性) : propertycode

  • jQuery 中的:attr() 對應原生JS中的 setAttribute() / getAttribute;對象

  • jQuery 中的:prop() 對應原生JS中 DOM對象.property;ip


在IE中

  • 在更早版本的 Windows Internet Explorer 中,內容屬性在 JavaScript 對象上表示爲文檔對象模型 (DOM) expando。element

    即: HTML屬性attr === DOM屬性prop
  • 從 Windows Internet Explorer 91 開始,內容屬性再也不鏈接到 DOM expando,這提升了 Internet Explorer 和其餘瀏覽器之間的可互操做性。文檔

    即IE10+中: HTML屬性attr !== DOM屬性prop

解讀

  • 「內容屬性-attr」在是 HTML 源中指定的屬性,例如,<element attribute1="value" attribute2="value">。許多內容屬性都做爲 HTML 的一部分進行預約義;HTML 還支持其餘用戶定義的內容屬性。get

  • 「dom屬性-prop」是從 JavaScript 中的對象檢索的值,可經過 . 運算符得到值, 例如 document.all["myelement"].domExpando。JavaScript 還支持其餘用戶定義的屬性。class


約定

由於IE9+ 經過 var divExpando = div.myAttr; 的方法得到 內容屬性(HTML屬性)會致使 獲得一個未定義的值,因此咱們約定使用代碼:方法

var divExpando = div.getAttribute("myAttr"); // 獲得有價值的HTML屬性


  1. 在 IE8 和之前版本中(包括 IE8 標準模式和 IE9 中的之前模式),仍然存在 myAttr 內容屬性 表示存在 myAttr DOM expandovar divExpando = div.myAttr; // divExpando 任然會獲得有價值的定義
相關文章
相關標籤/搜索