// JavaScript Document 2010-06-03 zhoux //年份下拉框Id,月份下拉框Id,日期下拉框Id,起始年(null则默认1970),结束年(null则默认当前年) function TearoomRoom(year, month, day, startYear, endYear) { if (null == startYear) { startYear = "1970"; } if (null == endYear) { endYear = new Date().getFullYear(); } //输出年 for (; startYear <= endYear; startYear++) { $("#" + year).append("<option value=" + startYear + ">" + startYear + "</option>"); } //输出月 for (var i = 1; i <= 12; i++) { $("#" + month).append("<option value=" + ((i < 10) ? "0" + i : i) + ">" + i + "</option>"); } //输出日期 if (null != day) { $(document).ready(function () {//添加onchange事件 $("#" + year).change(function () { displaySelectDay($("#" + year).val(), $("#" + month).val(), day); }); $("#" + month).change(function () { displaySelectDay($("#" + year).val(), $("#" + month).val(), day); }); }); displaySelectDay($("#" + year).val(), $("#" + month).val(), day); } } //是否是润年 function isLeapYear(year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return true; } return false; } //显示日下拉框 function displaySelectDay(year, month, selectDayId) { if (null != year && null != month && !isNaN(year) && !isNaN(month)) { var monthArr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];//月份的天数 var day = (isLeapYear(year) && month == 2) ? monthArr[month - 1] + 1 : monthArr[month - 1]; $("#" + selectDayId + ">option").remove();//清空option项 for (var i = 1; i <= day; i++) { $("#" + selectDayId).append("<option value=" + ((i < 10) ? "0" + i : i) + ">" + i + "</option>"); } } }
以上是一个方法,使用了JQuery 它针对id 添加onchange 事件,调用如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>年月日级联更新</title> <script language="javascript" type="text/javascript" src="../JS/jquery-1.4.1.js"></script> <script language="javascript" type="text/javascript" src="dateSelect.js"></script> <script language="javascript" type="text/javascript"> //new TearoomRoom("year","month","day","1995","2020") 分别是年Id,月Id,日Id,起始年,终止年 $(document).ready(function(){$("#timeButton").click(function(){new TearoomRoom("year","month","day","1995","2020");});}); //如不输入起始年1970~当前年 //$(document).ready(function(){$("#timeButton").click(function(){new TearoomRoom("year","month","day",null,null);});}); //日期可以为null,此时不操作日期 //$(document).ready(function(){$("#timeButton").click(function(){new TearoomRoom("year","month",null,"1995","2020");});}); </script> </head> <body> <select id="year" name="year"> </select> <select id="month" name="month"> </select> <select id="day" name="day"> </select> <button type="button" id="timeButton"> 设置时间 </button> </body> </html>