我的HTML代码如下:
<div id="detail">
<div class="d_left">
Page <strong>1</strong> of 107
</div>
<div class="d_center">
<table>
<tr>
<td><a href="#">Previous</a> | <a href="#">Next</a>
<img src="/webProject/store/images/arrow.png" align="absmiddle" alt="">
</td></tr></table>
</div>
<div class="d_right">
Sort by:
<select name="featured" size="1" id="item1">
<option>Featured Items1</option>
<option>Featured Items2</option>
<option>Featured Items3</option>
<option>Featured Items4</option>
</select>
</div>
</div>
现在,我想从<select name="featured" size="1" id="item1">
读取所选值。
我怎么能用JavaScript做到这一点?
答案 0 :(得分:14)
document.getElementById("item1").value;
答案 1 :(得分:5)
sushil bharwani解决方案的更优雅变体
function $(id){return document.getElementById(id);}
var select = $("item1");
select.onchange = function() {
var selIndex = select.selectedIndex;
var selValue = select.options(selIndex).innerHTML;
}
由于Shadow Wizard不喜欢这个解决方案,我希望他会喜欢这个:
var select = document.getElementById("item1");
select.onchange = function() {
var selIndex = select.selectedIndex;
var selValue = select.options(selIndex).innerHTML;
}
这两个示例的主要思想是减少getElementById的使用。没有必要多次执行它 - 因此minimizing the access to the DOM。
对于那些有足够勇气的人来说,有一件新事querySelector()
mdn,msdn IE dev center,msdn,w3 spec :
var select = document.querySelector("#item1");
答案 2 :(得分:3)
document.getElementById("item1").onchange = function(){
var selIndex = document.getElementById("item1").selectedIndex;
var selValue = document.getElementById("item1").options[selIndex].innerHTML;
}
答案 3 :(得分:1)
function delivery(x){
var country = x.value;
document.getElementById('lala').innerHTML = country;
}
<div id="lala"></div>
<form action="" method="post">
<select name="country" id="country" onChange="delivery(this)">
<option value='lala'>Select Country</option>
<option value='United_Kingdom'>United Kingdom</option>
<option value='Russia'>Russia</option>
<option value='Ukraine'>Ukraine</option>
<option value='France'>France</option>
<option value='Spain'>Spain</option>
<option value='Sweden'>Sweden</option>
</select>
</form>
以下是我如何解决我选择欧盟国家的问题(我删除了大部分国家以使我的代码更短)..作为javascript的新手...我还需要学习javascript库。