在日曆應用程序中,我有一個簡單的選擇,其選項標籤的值爲0-11,相應的月份。我可以在單月(從十二月到一月)周而復始,但我無法以其他方式工作。它只顯示2月和12月。如何通過HTML循環選擇<option>點擊值?
這裏的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);
});
太棒了,就是這樣!謝謝!! –
雖然 - 我試着將selectedMonth var投射到一個數字,我必須刪除它,所以我不能完美地複製它,像$('#MonthName').val(Number(selectedMonth + 1))'' - 那會不會做同樣的事情?我敢肯定我的語法錯了!爲什麼我在去一月的時候會工作,而不是在我去十二月的時候? –
您需要轉換變量,而不是加法結果:'.val(Number(selectedMonth)+1)'。 – Barmar