代碼很簡單,這裡就不多廢話了,直接給大家源碼吧
<!doctype html> <html> <head> <title>年月日</title> </head> <body onLoad="init()"> <select id="year" onChange="swap_day()"></select>年 <select id="month" onChange="swap_day()"></select>月 <select id="day"></select>日 </body> <script> var month_big = new Array("1","3","5","7","8","10","12"); //包含所有大月的數組 var month_small = new Array("4","6","9","11"); //包含所有小月的數組 //頁面加載時調用的初始化select控件的option的函數 function init() { var select_year = document.getElementById("year"); //獲取id為"year"的下拉列表框 var select_month = document.getElementById("month"); //獲取id為"month"的下拉列表框 var select_day = document.getElementById("day"); //獲取id為"day"的下拉列表框 //將年份選項初始化,從1980到2000 for(var i = 1980; i <= 2000; i++) { select_year_option = new Option(i, i); select_year.options.add(select_year_option); } //將月份選項初始化,從1到12 for(var i = 1; i <= 12; i++) { select_month_option = new Option(i, i); select_month.options.add(select_month_option); } //調用swap_day函數初始化日期 swap_day(); } //判斷數組array中是否包含元素obj的函數,包含則返回true,不包含則返回false function array_contain(array, obj) { for (var i = 0; i < array.length; i++) { if (array[i] === obj) { return true; } } return false; } //根據年份和月份調整日期的函數 function swap_day() { var select_year = document.getElementById("year"); //獲取id為"year"的下拉列表框 var select_month = document.getElementById("month"); //獲取id為"month"的下拉列表框 var select_day = document.getElementById("day"); //獲取id為"day"的下拉列表框 select_day.options.length = 0; //在調整前先清空日期選項裡面的原有選項 var month = select_month.options[select_month.selectedIndex].value; //獲取被選中的月份month //如果month被包含在month_big數組中,即被選中月份是大月,則將日期選項初始化為31天 if(array_contain(month_big, month)) { for(var i = 1; i <= 31; i++) { select_day_option = new Option(i, i); select_day.options.add(select_day_option); } } //如果month被包含在month_small數組中,即被選中月份是小月,則將日期選項初始化為30天 else if(array_contain(month_small, month)) { for(var i = 1; i <= 30; i++) { select_day_option = new Option(i, i); select_day.options.add(select_day_option); } } //如果month為2,即被選中的月份是2月,則調用initFeb()函數來初始化日期選項 else { initFeb(); } } //判斷年份year是否為閏年,是閏年則返回true,否則返回false function isLeapYear(year) { var a = year % 4; var b = year % 100; var c = year % 400; if( ( (a == 0) && (b != 0) ) || (c == 0) ) { return true; } return false; } //根據年份是否閏年來初始化二月的日期選項 function initFeb() { var select_year = document.getElementById("year"); //獲取id為"year"的下拉列表框 var select_day = document.getElementById("day"); //獲取id為"day"的下拉列表框 var year = parseInt(select_year.options[select_year.selectedIndex].value); //獲取被選中的年份並轉換成Int //如果是閏年,則將日期選項初始化為29天 if(isLeapYear(year)) { for(var i = 1; i <= 29; i++) { select_day_option = new Option(i, i); select_day.options.add(select_day_option); } } //如果不是閏年,則將日期選項初始化為28天 else { for(var i = 1; i <= 28; i++) { select_day_option = new Option(i, i); select_day.options.add(select_day_option); } } } </script> </html>
以上所述就是本文的全部內容了,希望大家能夠喜歡。