n. 性質,性能;財產;所有權
英英釋義:
any area set aside for a particular purpose “the president was concerned about the property across from the White House”
同義詞:place
something owned; any tangible or intangible possession that is owned by someone “that hat is my property”; ” he is a man of property”
同義詞:belongings | holding | material possession
a basic or essential attribute shared by all members of a class
a construct whereby objects or individuals can be distinguished “self-confidence is not an endearing property”
同義詞:attribute | dimension
any movable articles or objects used on the set of a play or movie
同義詞:prop
重點看2、3、4條。
再看attribute:
代碼如下:
attribute [ə'tribju:t, 'ætribju:t]
n. 屬性;特質
vt. 歸屬;把…歸于
英英釋義:
n.
a construct whereby objects or individuals can be distinguished
同義詞:property | dimension
an abstraction belonging to or characteristic of an entity
v.
attribute or credit to ”We attributed this quotation to Shakespeare”
同義詞:impute | ascribe | assign
decide as to where something belongs in a scheme
同義詞:assign
property,attribute都作“屬性”解,但是attribute更強調區別于其他事物的特質/特性,而在這篇文章中也提交到attribute是property的子集。
而在JavaScript中,property和attribute更是有明顯的區別。眾所周知,setAttribute是為DOM節點設置/添加屬性的標準方法:
var ele = document.getElementById("my_ele"); ele.setAttribute("title","it's my element");但很多時候我們也這樣寫:
ele.title = "it's my element";如果不出什么意外,他們都運行的很好,它們似乎毫無區別?而且通常情況下我們還想獲取到我們設置的“屬性”,我們也很愛這樣寫:
alert(ele.title);這時候,你便會遇到問題,如果你所設置的屬性屬于DOM元素本身所具有的標準屬性,不管是通過ele.setAttribute還是ele.title的方式設置,都能正常獲取。但是如果設置的屬性不是標準屬性,而是自定義屬性呢?
ele.setAttribute('mytitle','test my title'); alert(ele.mytitle); //undefined alert(ele.getAttribute('mytitle')); //'test my title' ele.yourtitle = 'your test title'; alert(ele.getAttribute('yourtitle')); //null alert(ele.yourtitle); //'your test title'通過setAttribute設置的自定義屬性,只能通過標準的getAttribute方法來獲取;同樣通過點號方式設置的自定義屬性也無法通過 標準方法getAttribute來獲取。在對自定義屬性的處理方式上,DOM屬性的標準方法和點號方法不再具有任何關聯性(上訴代碼在IE6-有兼容性 問題,后面會繼續介紹)。
這種設置、獲取“屬性”的差異性,究其根源,其實也是property與attribute的差異性所致。
通過點號設置的“屬性”其實是設置的property,如上所說attribute是property的子集,那么點號設置的property自然無法通過只能獲取attribute的getAttribute方法來獲取。
property and attribute
照圖似乎更易理解,getAttribute無法獲取到不屬于attribute的property也是理所應當。但是這時候你會發現另外一個問題,通過setAttribute設置的屬性,同樣也應該屬于property,那么為何無法通過點號獲取?
我們換種理解,只有標準屬性才可同時使用標準方法和點號方法,而對于自定義屬性,標準方法和點號方法互不干擾。
自定義屬性互不干擾
那么,在JavaScript中attribute并不是property的子集,property與attribute僅存在交集,即標準屬性,這樣疑問都可得到合理的解釋。但在IE9-中,上訴結論并不成立。IE9-瀏覽器中,除了標準屬性,自定義屬性也是共享的,即標準方法和點號皆可讀寫。
成功設置的attribute都會體現在HTML上,通過outerHTML可以看到attribute都被添加到了相應的tag上,所以如果 attribute不是字符串類型數據都會調用toString()方法進行轉換。但是由于IE9-中,標準屬性與自定義屬性不做區 分,attribute依然可以是任意類型數據,并不會調用toString()轉換,非字符串attribute不會體現在HTML上,但更為嚴重的問 題是,這樣很容易就會導致內存泄漏。所以如果不是字符串類型的自定義屬性,建議使用成熟框架中的相關方法(如jQuery中的data方法)。
getAttribute與點號(.)的差異性
雖然getAttribute和點號方法都能獲取標準屬性,但是他們對于某些屬性,獲取到的值存在差異性,比如href,src,value等。
Test Link
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com