2016-03-15 166 views
1

我有以下代碼。但警報不顯示選項的名稱,而是顯示「未定義」。對於價值,它顯示正確的內容。未定義的選項名稱javascript

<select id="test" name="select_decision" onchange="javascript: 
var activeText = this.options[this.selectedIndex].value 
var activeOption = this.options[this.selectedIndex].name; 
alert(activeOption); 
"> 

一個選項的一個例子是:

<option value="test" name="test_name">Test</option> 

一直在尋找對谷歌的答案,但無法找到一個!

+1

[HTML選項元素(https://developer.mozilla.org/en/docs/Web/HTML/Element/選項)沒有'name'屬性。 – Jamiec

回答

5

option elements沒有name屬性,所以沒有反映它的屬性,所以optionElement.nameundefined

雖然你可以通過得到optionElement.getAttribute("name")該屬性的值,一般來說,如果你想自定義屬性添加到一個元素,你應該使用data-* prefix

+0

謝謝!結束了使用標籤,而不是! – coffeeak

+0

我相信OP應該只是抓住'select'的值而不是... –

+1

@coffeeak:'label'用於選項的文本。 'option'元素的'label'屬性*和*文本內容是無效的。這個'名字'的東西你的目的/目標是什麼? –

-1

嘗試使用htmlElement.getAttribute(attrName)。所以,在你的情況下,嘗試使用

var activeOption = this.options[this.selectedIndex].getAttribute('name'); 

,而不是你

var activeOption = this.options[this.selectedIndex].name;