来自http://tunps.com/javascript-date-menu
百度知道有人提问:如题: 有三个下拉列表,分别为年,月,日。年和月的好实现,循环即可。但是天数却要根据年和月来定。循环次数要看条件。 怎样实现这样的代码。 期待解决……于是就花了一下午的时间弄了一个:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.||g/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.||g/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JavaScript年月日下拉菜单</title></head><body><div id="cc"><h1><a href="">JavaScript年月日下拉菜单</a></h1></div><div id="date_select||"> <select id="year"> </select>年 <select id="month"> </select>月 <select id="day"> </select>日</div><script>//code by tunpishuang at gmail dot com//2009.12.23yearList=document.getElementById("year");monthList=document.getElementById("month");dayList=document.getElementById("day");date={ init:function(fromYear,toYear,fromMonth,toMonth) { date.genYear(fromYear,toYear); date.genMonth(fromMonth,toMonth); if(window.addEventListener) { yearList.addEventListener('change',date.genDay,false); monthList.addEventListener('change',date.genDay,false); } else { yearList.attachEvent('onchange',date.genDay); monthList.attachEvent('onchange',date.genDay); } }, isLeapYear:function(year) { if ((year%400==0) || (year%100!=0) && (year%4==0)) { return 1; } else return 0; }, genYear:function(from,to) { //generate year if(from > to){return}; for(i=0;from< =to;i++,from++) { yearList.options[i]=new Option(from,from); } }, genMonth:function(from,to) { //generate monther for(i=0;from<=to;i++,from++) { monthList.options[i]=new Option(from,from); } }, genDay:function() { //generate days according to year and month if(!(yearList.options.selectedIndex > -1)) return; yearSelected=yearList.options[yearList.options.selectedIndex].text; if(!(monthList.options.selectedIndex > -1)) return; monthSelected=monthList.options[monthList.options.selectedIndex].text; //if dayList.options then remove all options if(dayList.options) { for(i=0;i<daylist .options.length;i++) { dayList.options[i]=null; } } if(monthSelected==1 || monthSelected==3 || monthSelected==5 || monthSelected==7 || monthSelected==8 || monthSelected==10 || monthSelected==12) { for(i=0;i<31;i++) { dayList.options[i]=new Option(i+1,i+1); } } else if(monthSelected==4 || monthSelected==6 || monthSelected==9 || monthSelected==11) { for(i=0;i<30;i++) { dayList.options[i]=new Option(i+1,i+1); } } else //Feburary { if(date.isLeapYear(yearSelected)) { for(i=0;i<29;i++) { dayList.options[i]=new Option(i+1,i+1); } } else { for(i=0;i<28;i++) { dayList.options[i]=new Option(i+1,i+1); } } } }}window.onload=date.init(1900,2100,1,12);</script></daylist></script></body></html> |