此函数返回
n最近几个月,包括当前月份:
function getLastMonths(n) { var months = new Array(); var today = new Date(); var year = today.getFullYear(); var month = today.getMonth() + 1; var i = 0; do { months.push(year + (month > 9 ? "" : "0") + month); if(month == 1) { month = 12; year--; } else { month--; } i++; } while(i < n); return months;}呼叫:
document.write(getLastMonths(4));
印刷品:
201211,201210,201209,201208
然后,在下拉框中添加这些值非常简单:
function writeMonthOptions() { var optionValues = getLastMonths(4); var dropDown = document.getElementById("monthList"); for(var i=0; i<optionValues.length; i++) { var key = optionValues[i].slice(4,6); var value = optionValues[i]; dropDown.options[i] = new Option(value, key); }}只需使用:
writeMonthOptions();



