javascript - 设置一个等于当前所选选项的变量

标签 javascript html

JavaScript:

function read() {
  var x =  document.getElementById("selectedcust").options[document.getElementById("selectedcust").selectedIndex].value;
  console.log(x);
}

html:

<select  id="selectedcust"  style="position: absolute; top:-8px;left: 80px;" onchange="read()">

基本上我希望变量x等于当前选定的选项。然而,就目前情况而言,每当您更改所选项目时,变量都不会更改。

编辑:对于也尝试执行此操作的任何人,请注意我的上述代码确实有效。问题出在其他地方。

最佳答案

只是基于 Sachin Kadam 的建议,您可以通过传递“this”来大大缩短该语句。

 <select  id="selectedcust"  style="position: absolute; top:8px;left: 80px;" onchange="read(this)">
     <option>aaaaaaa</option>
     <option>bbbbbbb</option>
     <option>ccccccc</option>
     <option>ddddddd</option>
     <option>eeeeeee</option>
 </select>
<script>
         function read(e) {
            var x =  e.options[e.selectedIndex].value;
             console.log(x);
            }
</script>

http://jsfiddle.net/5oLrwkxm/1/

关于javascript - 设置一个等于当前所选选项的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31972616/

相关文章:

javascript - typescript ,如何引用未导出的 OAuth2Client? google-api-nodejs-客户端

javascript - 强制 Accordion 关闭所有选项卡

javascript - 将模态转换为 div

javascript - 添加或删除表中的单个列

html - 这个大会网站是如何淡入淡出的?

javascript - 如何在 d3.js 中制作单独的 .js 文件饼图?

javascript - 如何在React JS中实现按下回车键时的onChange事件

javascript - cakephp Controller 中的失败条件后重定向到模式(自动打开 Bootstrap 模式)

javascript - jQuery flot 去除条形边框

javascript - 以 ngIf 为条件禁用/启用 ngFor 内的多个按钮