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