我创建了一个函数,用于创建自我月份开始的x年的日期范围。但是,我已经硬编码了纠正月份的值,这使得它无法延伸。我想这样做,以便这个脚本更好地工作,而不必使用硬编码" if"我的for循环中的语句。谢谢你的帮助!
CodePen:http://codepen.io/anon/pen/lJGbE
HTML:
<button onclick="dateRange(2)">Create Select Range</button>
JS:
function dateRange(x) {
var startDay = 1;
var numYears = x;
var numMonths = ((numYears * 12) + 1);
var d = new Date();
var month = d.getMonth();
month = month + 1;
var year = d.getFullYear();
var createOptions = []; //array storage for options
createOptions.push("<option selected='selected'>Select...</option>");
for (i = 0; i < numMonths; i++) {
var tempMonth = month + i;
var tempYear = 0;
if ((tempMonth > 12) && (tempMonth <= 24)) {
tempMonth = tempMonth - 12;
tempYear = 1;
}
else if ((tempMonth > 24) && (tempMonth <= 36)) {
tempMonth = tempMonth - 24;
tempYear = 2;
}
switch (tempMonth) {
case 1: simpleMonth = "Jan"; break;
case 2: simpleMonth = "Feb"; break;
case 3: simpleMonth = "Mar"; break;
case 4: simpleMonth = "Apr"; break;
case 5: simpleMonth = "May"; break;
case 6: simpleMonth = "Jun"; break;
case 7: simpleMonth = "Jul"; break;
case 8: simpleMonth = "Aug"; break;
case 9: simpleMonth = "Sep"; break;
case 10: simpleMonth = "Oct"; break;
case 11: simpleMonth = "Nov"; break;
case 12: simpleMonth = "Dec"; break;
}
var makeDate = tempMonth + "/" + startDay + "/" + (year + tempYear);
var makeSimple = simpleMonth + "-" + (year + tempYear);
createOptions.push("<option value='" + makeDate + "'>" + makeSimple + "</option>");
}
//return (createOptions);
alert(createOptions);
}
答案 0 :(得分:0)
解决:(不需要使用for循环中的索引并使用++而是在for循环之外移动tempMonth的声明。
CodePen:http://codepen.io/anon/pen/aIlfG
JS:
function dateRange(x) {
var startDay = 1;
var numMonths = ((x * 12) + 1);
var d = new Date();
var month = d.getMonth();
month = month + 1;
var year = d.getFullYear();
var createOptions = []; //array storage for options
createOptions.push("<option selected='selected'>Select...</option>");
var tempMonth = month - 1;
var tempYear = 0;
for (i = 0; i < numMonths; i++) {
if (tempMonth >= 12) {
tempMonth = tempMonth - 11;
tempYear++;
} else {
tempMonth++;
}
switch (tempMonth) {
case 1: simpleMonth = "Jan"; break;
case 2: simpleMonth = "Feb"; break;
case 3: simpleMonth = "Mar"; break;
case 4: simpleMonth = "Apr"; break;
case 5: simpleMonth = "May"; break;
case 6: simpleMonth = "Jun"; break;
case 7: simpleMonth = "Jul"; break;
case 8: simpleMonth = "Aug"; break;
case 9: simpleMonth = "Sep"; break;
case 10: simpleMonth = "Oct"; break;
case 11: simpleMonth = "Nov"; break;
case 12: simpleMonth = "Dec"; break;
}
var makeDate = tempMonth + "/" + startDay + "/" + (year + tempYear);
var makeSimple = simpleMonth + "-" + (year + tempYear);
createOptions.push("<option value='" + makeDate + "'>" + makeSimple + "</option>");
}
//return (createOptions);
alert(createOptions);
}