使用javascript代码从HTML的select标记读取所选值
我的HTML代码如下:使用javascript代码从HTML的select标记读取所选值,javascript,html,Javascript,Html,我的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> |
<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>
第1页,共107页
|
排序方式:
特色项目1
特色项目2
特色项目3
特色项目4
现在,我想从
读取所选值。
如何使用JavaScript实现这一点?更优雅的解决方案变体
document.getElementById("item1").value;
由于我不喜欢这种解决方案,我希望他会喜欢:
var select = document.getElementById("item1");
select.onchange = function() {
var selIndex = select.selectedIndex;
var selValue = select.options(selIndex).innerHTML;
}
这两个示例的主要思想是减少getElementById的使用。重复执行一次没有意义——因此
对于那些感到足够勇敢的人:)有一个新东西querySelector()
,:
功能交付(x){
var国家=x.0价值;
document.getElementById('lala').innerHTML=country;
}
选择国家
大不列颠联合王国
俄罗斯
乌克兰
法国
西班牙
瑞典
以下是我如何解决选择欧盟国家的问题(我删除了其中的大部分,以缩短代码)。。因为我是javascript新手。。我仍然需要学习javascript库。James Allardice:你的意思是没有必要像detai1那样做。item1@Makram这不起作用,因为当前html在选项中不包含值。@sushil bharwani实际上它会起作用,因为第一个选项总是被选中-一行中有两个错误:
options
是数组,option
元素没有innerHTML,只有值或文本。好的,现在你在所有主要浏览器中修复了数组部分(使用方括号)-innerHTML很久以前对我不起作用,我猜它是“修复”的在IE7及以上版本中,您在哪里看到jQuery?为什么您认为它可以使用?@Shadow-Wizard它是纯JavaScript-这里不涉及jQuery。它不是选择器,而是getElementById的缩写。函数名可以以a-z a-z$开头。对不起,我以前与IE7合作的时间太长了,现在选项
也可以作为函数访问,$
的东西也让我感到困惑。取消投票,将在将来花费更多时间阅读和测试。选择.options(selIndex)这不起作用,选择.options[selIndex]这起作用当您想阅读它时?回应什么事件?
function $(id){return document.getElementById(id);}
var select = $("item1");
select.onchange = function() {
var selIndex = select.selectedIndex;
var selValue = select.options(selIndex).innerHTML;
}
var select = document.getElementById("item1");
select.onchange = function() {
var selIndex = select.selectedIndex;
var selValue = select.options(selIndex).innerHTML;
}
var select = document.querySelector("#item1");
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>