在日历应用程序中,我有一个简单的选择,其中包含相应月份的值为 0-11 的选项标记。我可以单向循环几个月(从十二月到一月),但我无法让它以另一种方式工作。它只显示二月和十二月。
这是a jsfiddle显示我已经做过的事情。
这是 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
的宽度——点击右箭头很困难,因为它随着月份的变化而不断移动。
关于javascript - 如何在单击时循环选择 HTML 选择 <option> 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19279218/