1. 程式人生 > 其它 >properties 和 attributes的區別

properties 和 attributes的區別

在編寫HTML原始碼時,可以在HTML元素上定義屬性(attribute)。然後,一旦瀏覽器解析了您的程式碼,就會建立一個相應的DOM節點。該節點是一個物件,因此它具有屬性(properties)。

比如:<input type="text" value="Name:">

它有兩個attributes,type和value。一旦瀏覽器解析了這段程式碼,就會建立一個HTMLInputElement物件,該物件將包含幾十個properties,比如:accept、accessKey、align、alt、attributes、autofocus、baseURI、checked、childElementCount、childNodes、children、classList、className、clientHeight等。

對於給定的DOM節點物件,properties是該物件的屬性,而attributes是該物件的attributes屬性的元素。相應的DOM節點將具有id、型別和值的properties(等等)。以下用英文比較好理解

  • Theidproperty is areflected propertyfor theidattribute: Getting the property reads the attribute value, and setting the property writes the attribute value.idis apurereflected property, it doesn't modify or limit the value.

  • Thetypeproperty is areflected propertyfor thetypeattribute: Getting the property reads the attribute value, and setting the property writes the attribute value.typeisn't a pure reflected property because it's limited toknown values(e.g., the valid types of an input). If you had<input type="foo">

    , thentheInput.getAttribute("type")gives you"foo"buttheInput.typegives you"text".

  • In contrast, thevalueproperty doesn't reflect thevalueattribute. Instead, it's thecurrent valueof the input. When the user manually changes the value of the input box, thevalueproperty will reflect this change. So if the user inputs"John"into the input box, then:

    theInput.value // returns "John"
    

    whereas:

    theInput.getAttribute('value') // returns "Name:"
  • value properties反映輸入框中的當前文字內容,而value attributes包含來自HTML原始碼的value屬性的初始文字內容。因此,如果你想知道當前文字框中有什麼,讀取properties。但是,如果您想知道文字框的初始值是多少,請讀取attributes。或者您可以使用defaultValue屬性,它是value attributes的純粹反映
  • theInput.value                 // returns "John"
    theInput.getAttribute('value') // returns "Name:"
    theInput.defaultValue          // returns "Name:"
  • 有幾個properties直接反映了它們的attributes(rel, id),有些是直接反映了稍微不同的名稱(htmlFor反映了for attribute,className反映了class attribute),許多properties反映了它們的attributes,但有限制/修改(src, href, disabled, multiple),等等。該規範涵蓋了各種反射。
  • disabled是一個特殊的屬性,比如一個button的disabledproperties 預設是false,這個按鈕就是啟用的。當你新增disabled attributes時,會將properites的disabled轉化為true,這個按鈕就被禁用了。 新增或者刪除disabled attributes會啟用或忌用按鈕 ,但是這個disabled的值是true或者false是沒意義的。所以<button disabled="false">Still Disabled</button>.的按鈕還是禁用的。想改變按鈕啟用或禁用狀態,要改變disabled properties,這就是properties存在的意義!(類似element的ui框架中,button元件<Button :disabled="false">enable</Button> 是有效的,這是因為element的內部做了處理)
  • The HTML attribute and the DOM property are not the same thing, even when they have the same name.