我正在尝试使用下拉列表中的javascript显示本月的最后3个月(包括总计4个月)
function writeMonthOptions() { var months = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"); var today = new Date(); var date = new Date(today); date.setFullYear(date.getFullYear() - 1); var dropDown = document.getElementById("Month_list"); var i = today.getMonth(); var optionNames; var optionValues; var beanData = '<s:property value="month" />'; while (i < (today.getMonth() + 4)) { optionNames = months[i]; optionValues = today.getFullYear() + '' + months[i]; dropDown.options[i++] = new Option(optionNames, optionValues); if (beanData) { if (beanData == (today.getFullYear() + "" + monthsInd[today .getMonth()])) { dropDown.selectedIndex = i - 1; } } } }
简单来说,在视图部分显示当月和前三个月的下拉列表。后端,则需要以[YYYYMM]的身份提交。
如果bean中已经存在值,则在下拉列表中将其显示为选中状态。[保证将在这4个月内]
此函数返回n最近几个月,包括当前月份:
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();