28

我正在尝试创建一个可以选择下一个选项的按钮。

所以,我有一个带有几个选项的选择(id=selectionChamp),下一个输入(id=fieldNext),我尝试这样做:

$('#fieldNext').click(function() {
    $('#selectionChamp option:selected', 'select').removeAttr('selected')
          .next('option').attr('selected', 'selected');

    alert($('#selectionChamp option:selected').val());      
});

但我无法选择下一个选项.. 谢谢!

4

8 回答 8

38
$('#fieldNext').click(function() {
    $('#selectionChamp option:selected').next().attr('selected', 'selected');

    alert($('#selectionChamp').val());      
});

@VisioN 的更好回答:https ://stackoverflow.com/a/11556661/1533609

于 2012-07-19T08:15:57.937 回答
22
$("#fieldNext").click(function() {
    $("#selectionChamp > option:selected")
        .prop("selected", false)
        .next()
        .prop("selected", true);
});​

演示:http: //jsfiddle.net/w9kcd/1/

于 2012-07-19T08:17:35.650 回答
10

没有 jQuery 也很简单。一旦达到最后一个选项,这个选项将循环到第一个选项:

function nextOpt() {
  var sel = document.getElementById('selectionChamp');
  var i = sel.selectedIndex;
  sel.options[++i%sel.options.length].selected = true;
}

window.onload = function() {
  document.getElementById('fieldNext').onclick = nextOpt;
}

一些测试标记:

<button id="fieldNext">Select next</button>
<select id="selectionChamp">
 <option>0
 <option>1
 <option>2
</select>
于 2012-07-19T08:39:57.883 回答
3
$(function(){
  $('#button').on('click', function(){
    var selected_element = $('#selectionChamp option:selected');
    selected_element.removeAttr('selected');
    selected_element.next().attr('selected', 'selected');

    $('#selectionChamp').val(selected_element.next().val());

  });
});

http://jsbin.com/ejunoz/2/edit

于 2012-07-19T08:24:19.373 回答
2

我希望这样的按钮能够循环通过选项,并触发更改事件。这是可能的解决方案:

$("#fieldNext").click(function() {
  if ($('#selectionChamp option:selected').next().length > 0) 
    $('#selectionChamp option:selected').next().attr('selected', 'selected').trigger('change');
  else $('#selectionChamp option').first().attr('selected', 'selected').trigger('change');
});

这是 jsFiddle:http: //jsfiddle.net/acosonic/2cg9t17j/3/

于 2018-12-06T06:33:27.700 回答
0
$('#fieldNext').click(function() {
$('#selectionChamp option:selected').removeAttr('selected')
      .next('option').attr('selected', 'selected');

alert($('#selectionChamp option:selected').val());      
});
于 2012-07-19T08:17:19.897 回答
0

试试这个 :

    $(document).ready(function(){
        $("#fieldNext").on("click",function(){
            $optionSelected = $("#selectionChamp > option:selected");
            $optionSelected.removeAttr("selected");
            $optionSelected.next("option").attr("selected","selected");       
        });
    });
于 2012-07-19T08:18:11.847 回答
0

如果除了选项元素之外还有选项组元素,其他解决方案将不起作用。在这种情况下,这似乎有效:

var options = $("#selectionChamp option");
var i = options.index(options.filter(":selected"));
if (i >= 0 && i < options.length - 1) {
    options.eq(i+1).prop("selected", true);
}

(你可能认为 for 的表达式i也可以写成options.index(":selected"),但这并不总是有效。我不知道为什么,欢迎解释。)

于 2013-11-08T14:17:06.500 回答