[英]How can I cycle through HTML select <option> values on click?
在日历应用程序中,我有一个简单的选择,其对应选项月的选项标签值为0-11。 我可以单月(从12月到1月)骑单车,但我无法以另一种方式骑车。 仅显示2月和12月。
这是HTML:
<select id="MonthName" class="form-control">
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<!-- etc, through 11 -->
</select>
<!-- 'Buttons' -->
<span class="chevron chevronLeft floatLeft">◀</span>
<span class="theMonth">Month</span>
<span class="chevron chevronRight floatRight">▶</span>
这是jQuery:
$('.chevron').on('click', function() {
// This if works perfectly, and will reset to 11 once the selectedMonth is 0
if ($(this).hasClass('chevronLeft')) {
var selectedMonth = $('#MonthName').val();
(selectedMonth != 0)
? $('#MonthName').val(selectedMonth - 1).trigger('change')
: $('#MonthName').val(11).trigger('change');
}
else {
// This doesn't work, I tried declaring the variable locally,
// different less/greater than expressions, but nothing works
var selectedMonth = $('#MonthName').val();
(selectedMonth !== 11)
? $('#MonthName').val(selectedMonth + 1).trigger('change')
: $('#MonthName').val(0).trigger('change');
}
});
$('#MonthName').on('change', function() {
var monthText =
$('#MonthName option:selected').text();
$('.theMonth').text(monthText);
});
更改:
var selectedMonth = $('#MonthName').val();
至:
var selectedMonth = parseInt($('#MonthName').val(), 10);
selectedMonth + 1
正在执行字符串连接而不是整数加法,因为selectedMonth
是字符串。
我还建议您指定“ theMonth
的宽度-单击右箭头很困难,因为它随着月份的变化而不断变化。
那是因为您正在将一个int和一个字符串串联在一起。
例如,执行'1' + 1
等于11
而不是2
。 在添加之前解析您的值:
$('#MonthName').val(parseInt(selectedMonth) + 1)
小提琴: http : //jsfiddle.net/mtJRn/21/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.