如何使箭头更改下拉选项

时间:2018-07-17 13:38:21

标签: javascript html

如果我有如下所示的下拉菜单:

<select>
    <option>Dog</option>
    <option>Cat</option>
    <option>Bird</option>
</select>

如何创建两个按钮,这些按钮在按下时会更改所选选项?因此,如果选择Cat并按下向上箭头,则Dog将变为选中状态。向下箭头也会发生同样的情况。选择Dog并单击向下箭头后,Cat将被选中。

2 个答案:

答案 0 :(得分:0)

您可以这样做:

var ddl = document.getElementById("s")

function change(x) {
  if (x.value === 'down') {
    ddl.selectedIndex = ddl.selectedIndex + 1
  } else {
    ddl.selectedIndex = ddl.selectedIndex - 1
  }
};
<select id="s">
  <option>Dog</option>
  <option>Cat</option>
  <option>Bird</option>
</select>
<input id="d" type="button" value="down" onclick="change(this); return false;">
<input id="u" type="button" value="up" onclick="change(this); return false;">

答案 1 :(得分:0)

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>
<script>
$(document).ready(function(){
$("#up").click(function(){
var selecteddata = $("#data option:selected").val();
  var next = parseInt(selecteddata)-1;
  $("#data").val(next.toString());
});

$("#down").click(function(){
var selecteddata = $("#data option:selected").val();
  var next = parseInt(selecteddata)+1;
  $("#data").val(next.toString());
 });
});
</script>
</head>
<body>

<select id="data">
<option value="0">Dog</option>
<option value="1">Cat</option>
<option value="2">Bird</option>
</select>
<input type="button" value="UP" id="up" />
<input type="button" value="Down" id="down" />
</body>
</html>