我想将当前月份和年份与接下来的 12 个月绑定(bind)到下拉菜单。我使用以下代码来绑定(bind)月份和年份。
function writeMonthOptions() {
var myselect = document.getElementById("drp6"), year = new Date().getFullYear();
var today = new Date();
var optionValues;
var gen = function (max) {
do {
optionValues = months[today.getMonth() + max] + ' ' + year;
myselect.add(new Option(optionValues, optionValues), null);
max++;
} while (max < 12);
}(0);
}
我的html代码:
<select name="drp6" id="drp6"></select>
但我得到如下选择选项:
2015年7月
2015年8月
2015年9月
2015年10月
2015年11月
2015 年 12 月
未定义 2015
未定义 2015
未定义 2015
未定义 2015
未定义 2015
如何解决?谢谢
最佳答案
由于只有 12 个月,如果您尝试在 optionValues = Months[today.getMonth() + max] + ' ' + Year;
中获取月份[13],则会被“取消罚款”那么。
此外,年份应该是一个相当大的部分,当您进入新的一年时,年份值应该是 2016。
您可以更改为:
//demo value.
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function writeMonthOptions() {
var myselect = document.getElementById("drp6"), year = new Date().getFullYear();
var today = new Date();
var optionValues;
var gen = function (max) {
var curMonth = today.getMonth();
var curYear = year; // presevere outer year value if you hava other use
do {
optionValues = months[curMonth] + ' ' + curYear;
myselect.add(new Option(optionValues, optionValues), null);
++curMonth;
// When months reach the 13th ele of months, advance to next year.
if (curMonth === months.length) {
++curYear;
curMonth = 0;
}
max++;
} while (max < 12);
}(0);
}
// test.
writeMonthOptions();
<select id="drp6"></select>
关于javascript - HTML 选择选项显示 future 12 个月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31311045/