[英]Select next option with jQuery
我正在嘗試創建一個可以選擇下一個選項的按鈕。
所以,我有一個帶有多個選項的選擇(id=selectionChamp),下一個輸入(id=fieldNext),我嘗試這樣做:
$('#fieldNext').click(function() {
$('#selectionChamp option:selected', 'select').removeAttr('selected')
.next('option').attr('selected', 'selected');
alert($('#selectionChamp option:selected').val());
});
但我不能選擇下一個選項..謝謝!
$('#fieldNext').click(function() {
$('#selectionChamp option:selected').next().attr('selected', 'selected');
alert($('#selectionChamp').val());
});
@VisioN 的更好回答: https ://stackoverflow.com/a/11556661/1533609
$("#fieldNext").click(function() {
$("#selectionChamp > option:selected")
.prop("selected", false)
.next()
.prop("selected", true);
});
演示: http : //jsfiddle.net/w9kcd/1/
沒有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>
$(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());
});
});
我希望這樣的按鈕通過選項循環,並觸發更改事件。 這是可能的解決方案:
$("#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/
$('#fieldNext').click(function() {
$('#selectionChamp option:selected').removeAttr('selected')
.next('option').attr('selected', 'selected');
alert($('#selectionChamp option:selected').val());
});
試試這個 :
$(document).ready(function(){
$("#fieldNext").on("click",function(){
$optionSelected = $("#selectionChamp > option:selected");
$optionSelected.removeAttr("selected");
$optionSelected.next("option").attr("selected","selected");
});
});
如果除了 option 元素之外還有 optiongroup 元素,則其他解決方案不起作用。 在這種情況下,這似乎有效:
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);
}
(你可能認為i
的表達式也可以寫成options.index(":selected")
,但這並不總是有效。我不知道為什么,歡迎解釋。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.