程序是这个样子的:首先采集用户输入的年份和月份,经过计算获取该月份的最大天数,并获取月份第一天是星期几。然后在表格中填充该月份的具体信息。 日历测试 function getMonthJuZhen(date){ if(arguments.length == 0){ throw new Error("need a date"); } if(arguments[0] == null){ throw new Error("date is null or undefined"); } if(arguments[0] instanceof Date){ var monthjuzhen = new Array(5); for(var r = 0 ; r < 5 ; r++){ monthjuzhen[r] = [0,0,0,0,0,0,0]; } var maxDay = getMaxDay(arguments[0]); arguments[0].setDate(1); var r = 0; var c = arguments[0].getDay(); for(var d = 1 ; d <= maxDay ; d++){ monthjuzhen[r][c] = d; if(c == 6){ if(r == 4){ r = 0; } else{ r++; } c = 0; } else{ c++; } } return monthjuzhen; } else{ throw new Error("need a date"); } } function getMaxDay(date){ if(arguments.length == 0){ throw new Error("need a date"); } if(arguments[0] == null){ throw new Error("date is null or undefined"); } if(arguments[0] instanceof Date){ var tempDate = new Date(arguments[0].toString()); if(arguments[0].getMonth() == 11){ tempDate.setFullYear((tempDate.getFullYear()+1)); tempDate.setMonth(0); } else{ tempDate.setMonth((tempDate.getMonth()+1)); } return Math.floor((tempDate.getTime()-arguments[0].getTime())/(1000*60*60*24)); } else{ throw new Error("need a date"); } } function updateDate(){ var yearInput = document.getElementById("yearinput"); var monthInput = document.getElementById("monthinput"); try{ var year = parseInt(yearInput.value); var month = parseInt(monthInput.value); if(isNaN(year)){ if(isNaN(month)){ monthInput.value = ""; } yearInput.value = ""; return; } if(isNaN(month)){ monthInput.value = ""; return; } if(month > 12 || month < 1){ monthInput.value = ""; return; } month--; var date = new Date(year,month); var monthjuzhen = getMonthJuZhen(date); var day; var dayvalue; for(var r in monthjuzhen){ for(var c in monthjuzhen[parseInt(r)]){ day = document.getElementById(r+"-"+c); dayvalue = monthjuzhen[parseInt(r)][parseInt(c)]; if(dayvalue == 0){ if(day.hasChildNodes()){ day.removeChild(day.firstChild); } day.onmouseover = null; day.onmouseout = null; day.onclick = null; continue; } if(day.hasChildNodes()){ day.firstChild.nodeValue = dayvalue; } else{ day.appendChild(document.createTextNode(dayvalue)); } day.setAttribute("date",year+"-"+month+"-"+dayvalue); day.onmouseover = function(){this.style.backgroundColor = "black";this.style.color = "white";}; day.onmouseout = function(){this.style.backgroundColor = "white";this.style.color = "black"}; day.onclick = subDate; } } } catch(e){ alert(e); } } function subDate(){ var date = this.getAttribute("date").match(/(\d+)-(\d+)-(\d+)/); alert(new Date(date[1],date[2],date[3])); } 年 月 更新 日 一 二 三 四 五 六 [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]