2011-12-08 113 views
11

所以我正在學習操作DOM我注意到一個有趣的事:Javascript:setAttribute()v.s. element.attribute =值設置「名稱」屬性

比方說,我想通過設置元素的name屬性」。 「點符號:

element.name = "someName"; 
console.log(document.getElementsByName("someName")[0]); // returns "undefined"?? 

但是如果我使用document.setAttribute()方法,它工作正常:

element.setAttribute("name", "someName"); 
console.log(document.getElementsByName("someName")[0]); // returns the element like it should. 

不知道爲什麼點符號方法在第一種情況下是行不通的。

爲什麼會發生這種情況?

+0

一般儘量避免使用'getElementsByName' – zzzzBov

+1

爲什麼要避免使用getElementsByName? –

+0

屬性可以使用點符號訪問,如果這是您希望訪問它們的方式。如果你想使用點符號訪問屬性,你需要引用obj.attributes.attributeName來檢索屬性和obj.attributes.attributeName.value來操縱它的值。與setAttribute或getAttribute相比,它很囉嗦。並且不推薦作爲解決方案,但不管如何,對於你的問題「爲什麼不在第一種情況下工作」這個問題的完整答案 - 必須包括「它的確如此。你只是在錯誤的地方尋找屬性和他們的價值觀。「 – Radiotrib

回答

11

我的猜測(因爲你沒有指定元素類型)是元素通常沒有name屬性,因此設置這樣的DOM屬性將不起作用。

例如,在input元素上設置name屬性將起作用。將其設置在div不會。

然而,它將工作,但與setAttribute()

jsFiddle

+0

先生,當我設置一些html元素屬性爲「未定義」,它不起作用,並繼續採取其以前的值。你能告訴我爲什麼是這樣嗎? –

0

當您使用element.name時,您正在訪問屬性/創建名爲「name」的屬性並設置其值。

但是,

同時使用,element.setAttribute( '名', 'someName'),實際上是設置屬性 '名稱'。

IE8及以下版本將屬性和屬性視爲一樣,bug已在IE9及以上版本中修復。
Safari,FireFox,Chrome對待屬性和屬性不同。

但是,如果您希望這樣做,您可以隨時創建您選擇的新屬性。

+1

部分答案...有限,並沒有解釋問題背後的原因 – Radiotrib

4

要延長一些其他的提供的答案...

屬性「名」只考慮少數特定對象有效DOM。據https://developer.mozilla.org/en-US/docs/DOM/element.name這些對象是:

<a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, 
<map>, <meta>, <object>, <param>, <select>, and <textarea> 

對於這些對象,您可以設置,獲取和改變使用object.name名稱屬性但對於任何其他DOM對象的屬性「名」是一個自定義屬性,並且必須使用SetAttribute()創建或者將它添加到HTML聲明中。創建完成後,您可以使用setAttribute()getAttribute()訪問它,也可以使用object.attributes.name.value直接引用其值,例如,查看http://jsfiddle.net/radiotrib/yat72/1/。順便說一句 - 有負載時的警告框是故意的 - 檢查代碼,看看爲什麼...

0
<head> 
<script> 
function test($count) { 
document.getElementById("test1").setAttribute("name","file-upload_" + $count); 
} 
</script> 
</head> 
<body> 

<p>some content</p> 
<input id="test1" type="file" name="file-upload" id="file-upload" /> 
<p>some other content</p> 
<script>test(1);</script> 
</body> 
2

(試圖解釋上述職位的部分更好的,單獨的,因爲它已經進入-ve評級,並且相信這篇文章會少一些,請進一步改進。)

***的property

當您使用,element.name,您要訪問現有property命名爲 「名」 或設置它的值。

Example 1: 
var div1 = document.getElementById("div1"); 
div1.textContent = "2"; 

***的attribute

但是,在使用,element.setAttribute('name','someName'),你實際上是設置attribute命名爲 '名'。 該屬性可以是現有的物業也

Example 2: 
var h1 = document.getElementById("H1"); 
h1.setAttribute("class", "democlass"); 

Example 3: 
var d = document.getElementById("d1"); 
d.setAttribute("name1", "value1"); 
1

當你使用,element.name,你訪問屬性/創建一個名爲「name」屬性並設置其值。