对于表单(form)中常用的select选项,经常牵涉到选取的option的index值、value值及文本中,本文结合着实例对其进行讲解。
一个select如下
<button type="button" id="pre" onclick()="pre()">pre</button><select id="choose" name ="choose" onchange ="getOptionName()"><option value="option1">option1</option><option value="option2">option2</option><option value="option3">option3</option><option value="option4">option4</option><option value="option5">option5</option></select><button type="button" id="next" onclick()="next()">next</button>

1.获取select对象;
var sel=document.querySelector(“#choose”);
2.获取select选中option的index值;
var index=sel.selectedIndex;
3.获取select选中的option的 value;
var val=sel.options[index].value;
4.获取select选中的option的text;
var text=sel.options[index].text;
<script>let sel = document.querySelector('#choose');let selarr = [...sel];let selarrLength = selarr.length;//select 的长度;function getOptionName(){let first = sel.selectedIndex; //获取改变后的option 值}function pre(){ //向前的选择let current = sel.selectedIndex; //目前option的indexif(current > 0 ){current--;sel[current].selected="ture"; //将改变后的option置为selected;}else{alert("已经达到第一个!")return false;}}function next(){ //向后选择let current= sel.selectedIndex;current++;console.log(current);if(current < selarrLength){sel[current].selected="ture";}else{alert("已经达到最后!");return false;}}</script>
```
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号