2014-10-08 98 views
0

標籤名稱我有這樣的HTML開始使用期權價值在JavaScript

<select id="tempSelect" > 
    <option value="F">Fahrenheit</option> 
    <option value="C">Celsius</option> 
</select> 

我想用標籤名稱未ID獲得選擇的選項值。 我試過這個使用document.getElementById()它工作正常,但我想通過標籤名稱來做到這一點。 我搜索了很多,但到目前爲止找不到解決方案。

這裏是我的Java Script代碼

var parent = document.getElementsByTagName('select'); 
var tempUnit = parent.options[parent.selectedIndex].value; 

回答

2

document.getElementsByTagName()返回HTMLCollection(這是一種數組),所以它確實有options性質。您可以使用索引訪問列表中的項目。

var parent = document.getElementsByTagName('select')[0]; 
 
var tempUnit = parent.options[parent.selectedIndex].value; 
 

 
document.querySelector('#result').innerHTML = tempUnit
<select id="tempSelect" > 
 
    <option value="F">Fahrenheit</option> 
 
    <option value="C" selected>Celsius</option> 
 
</select> 
 
<div id="result"></div>

+0

完美!非常感謝你 :) – farhangdon 2014-10-08 03:13:33