我有一个HTML选择3个选项,如下-
<select id="list">
<option value="environment" selected>Environment Facing (default)</option>
<option value="user">User Facing</option>
<option value="member">Member Facing</option>
</select>
我想做的是用一个按钮在这些值之间切换。这可能吗?我怎么能切换,如果第一个选项被选中,如果我点击按钮第二个选项被选中,如果第二个被选中后再次点击第三被选中。有什么办法我能做到吗?
一种方法可以是将可用的值放入数组中,并在该数组中找到当前选定值的索引,将其增加1,看看是否获得值。如果你得到了undefined
(这是你在一个不存在的索引上访问数组元素时得到的结果),你应该从数组的第一个元素开始。
const list = document.getElementById('list');
const values = [...list.options].map(({value}) => value);
document.getElementById("button").addEventListener("click", function() {
const currentValue = list.value;
list.value = values[values.indexOf(currentValue)+1] ?? values[0];
});
<select id="list">
<option value="environment" selected>Environment Facing (default)</option>
<option value="user">User Facing</option>
<option value="member">Member Facing</option>
</select>
<button id="button" type="button">Toggle</button>
增加select
的selectedIndex
,当你到达终点时绕起来。
document.getElementById("button").addEventListener("click", function() {
let list = document.getElementById("list");
let selected = list.selectedIndex;
selected = (selected + 1) % list.length;
list.selectedIndex = selected;
});
document.getElementById("show").addEventListener("click", function() {
let list = document.getElementById("list");
console.log(`Selected = ${list.value}`);
});
<select id="list">
<option value="environment" selected>Environment Facing (default)</option>
<option value="user">User Facing</option>
<option value="member">Member Facing</option>
</select>
<button id="button" type="button">Toggle</button>
<button id="show" type="button">Show selected</button>