HTML选择选项显示上去12个月
HTML selection option display on going 12 months
我想将当前月份和年份与未来12个月绑定到下拉列表。我使用下面的代码来绑定月份和年份。
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],那么它将是'未定义的'。
另外,year应该是一个相当大的部分,当你进入新的一年时,years的值应该是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>
您只需将months
索引更改为:(today.getMonth() + max) % today.getMonth()
。
EDIT change year:
你还需要适应年份,这给了我们:optionValues = months[index % months.length] + ' ' + (year + Math.floor(index / months.length));
这就是你需要改变的。
window.onload = function() {
function writeMonthOptions() {
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var myselect = document.getElementById("drp6"), year = new Date().getFullYear();
var today = new Date();
var optionValues;
var index;
var gen = function (max) {
do {
index = today.getMonth() + max;
optionValues = months[index % months.length] + ' ' + (year + Math.floor(index / months.length));
myselect.add(new Option(optionValues, optionValues), null);
max++;
} while (max < 12);
}(0);
}
writeMonthOptions();
};
<select name="drp6" id="drp6"></select>
相关文章:
- JavaScript过期标头可以't设置为12个月
- 浮动图-如何在x轴上显示第一个月和最后一个月的minTickSize:[2,“month&”]
- 减去2015-12-31的1个月得出2015-12-01
- JavaScript:打印前 12 个月 - “March”打印两次
- 如何像这样显示时间,例如:1秒前,1分钟前,1小时前,1个月前
- 在Javascript中获得下一个12个月的结果是混乱的
- 如何在 html 的下拉列表中绑定过去 12 个月
- 最近 12 个月在 Javascript 中
- 角度JS显示+1个月日期
- 前几个月的名称为 Leabels(例如 12 月 15 日 11 月 15 日),以代替新标题和新标题 2 标签
- 如何限制xml文件中显示的12个图像,并自动为其他图像创建页面
- 使用JavaScript显示日期+3个月
- JavaScript-过去12个月的列表
- 在dojo中为选定日期添加4个月并将其显示在文本框中
- 如何显示多个月的启动日期选择器
- 在表格中设置12个月后的新日期
- JQuery Monthpicker -显示前两个月的选项
- Javascript函数,它接受一个月/日期并显示12个月/日期
- Angularjs从一个选择框中按月筛选最近12个月的数据
- HTML选择选项显示上去12个月