选择';选择元素项';通过jQuery在两个按钮的帮助下

选择';选择元素项';通过jQuery在两个按钮的帮助下,jquery,html,select,Jquery,Html,Select,如何使用jQuery在HTML选择上有两个上下按钮? 我用这个向上按钮 $('#selectBox option:eq(' + $("#selectt").prop("selectedIndex")-1 + '3)') .prop('selected', true); 我认为我们还需要一些“如果”来知道我们是否达到了列表的末尾 html 试试这个 HTML 1. 2. 3. ↑ &达尔; Javascript var sel = $('#foo'); $('.dir'

如何使用jQuery在HTML选择上有两个上下按钮? 我用这个向上按钮

$('#selectBox option:eq(' + $("#selectt").prop("selectedIndex")-1 + '3)')
    .prop('selected', true);
我认为我们还需要一些“如果”来知道我们是否达到了列表的末尾

html

试试这个

HTML


1.
2.
3.
↑
&达尔;
Javascript

var sel = $('#foo');

$('.dir').on('click', function() {
    var btn = $(this),
        dir = btn.data('direction')
        currentIdx = sel.prop('selectedIndex'),
        newIdx = currentIdx + dir;
    if (newIdx < 0) newIdx = 0;
    if (newIdx >= sel[0].options.length) newIdx = sel[0].options.length - 1;
    sel.prop('selectedIndex', newIdx);
});
var sel=$('#foo');
$('.dir')。在('click',function()上{
var btn=$(此),
dir=btn.data('方向')
currentIdx=sel.prop('selectedIndex'),
newIdx=当前idx+dir;
如果(newIdx<0)newIdx=0;
如果(newIdx>=sel[0].options.length)newIdx=sel[0].options.length-1;
选择属性('selectedIndex',newIdx);
});
这里演示-

试试这个

$('#selectBox option:eq(' + $("#selectt option:selected").index()+')').prop("selected", "selected");
<select id="foo">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<button id="up" class="dir" data-direction="-1">&uarr;</button>
<button id="down" class="dir" data-direction="1">&darr;</button>
var sel = $('#foo');

$('.dir').on('click', function() {
    var btn = $(this),
        dir = btn.data('direction')
        currentIdx = sel.prop('selectedIndex'),
        newIdx = currentIdx + dir;
    if (newIdx < 0) newIdx = 0;
    if (newIdx >= sel[0].options.length) newIdx = sel[0].options.length - 1;
    sel.prop('selectedIndex', newIdx);
});
$('#selectBox option:eq(' + $("#selectt option:selected").index()+')').prop("selected", "selected");