自定义左右按钮(循环)调整下拉框内的值
最近需要一个功能左右按钮调整下拉框内的值,遇到了一个问题,就是只用左或右按钮将选项点到第一个选项后左右按钮就不起作用了,这个东西我调了半天也没发现原因,最后问了一下同事需要加上$("#ShiftGroup option").attr("selected",false);
,具体原因我没有整清楚,大概猜测原因是因为下拉选项只能选择一个,导致循环卡壳了,如果有知道具体原因的希望能指点指点
实际代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>情况</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<style type="text/css">
</style>
</head>
<body>
<form method="post" action="">
<input type="button" id="leftbutton" value="<">
<select name="ShiftGroup" id="ShiftGroup">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<input type="button" id="rightbutton" value=">">
<button id="subbutton" type="submit">提交</button>
</form>
<script>
var onselected=0;
var optionslength = $("#ShiftGroup option").length;
console.log(optionslength);
window.onload = function() {
onselected=$("#ShiftGroup").get(0).selectedIndex;
}
$("#leftbutton").click(function(){
$("#ShiftGroup option").attr("selected",false);
if(onselected==0){
$("#ShiftGroup option").eq(optionslength-1).attr("selected",true);
console.log($("#ShiftGroup").get(0).selectedIndex);
onselected=optionslength-1;
}else{
$("#ShiftGroup option").eq(onselected-1).attr("selected",true);
console.log($("#ShiftGroup").get(0).selectedIndex);
onselected--;
}
});
$("#rightbutton").click(function(){
$("#ShiftGroup option").attr("selected",false);
if(onselected==optionslength-1){
$("#ShiftGroup option").eq(0).attr("selected",true);
console.log($("#ShiftGroup").get(0).selectedIndex);
onselected=0;
}else{
$("#ShiftGroup option").eq(onselected+1).attr("selected",true);
console.log($("#ShiftGroup").get(0).selectedIndex);
onselected++;
}
});
$("#shiftGroup option[value='{{ShiftGroup}}']").attr("selected",true);
</script>
</body>
</html>