一個簡單的Javascript做的下拉框聯動,這是以前做介面原型時學習的一個例子,收藏了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html XMLns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>日期動態聯動示範</title>
<script type="text/Javascript">
var oYears,oMonths,oDays,isLeapYear;
var iy,im,id;
window.onload=function () {
initDate();
}
function initDate() {
isLeapYear=false;
oYears=document.getElementById('years'); //獲得year的select
oMonths=document.getElementById('months'); //獲得month的select
oDays=document.getElementById('days'); //獲得day的select
initYears(); //初始化年份
//設定三個select的onChange事件
oYears.onchange=chgYear;
oMonths.onchange=chgMonth;
oDays.onchange=chgDay;
}
function initYears() {
oYears.length=1;
var cYear=new Date().getYear();
for (var i=cYear-20;i<=cYear;i++) //從當前年份前20年開始迴圈,可以自己更改迴圈區間
{
var o=new Option(i.toString(),i.toString());
oYears.add(o);
}
}
function chgYear() {
try
{
isLeapYear=false;
var year=parseInt(this.options[this.selectedIndex].value); //獲得選擇的年份
//判斷是否是閏年,不懂公式的自己百度
if (year%4==0) isLeapYear=true;
if (year%100==0 && year%400!=0) isLeapYear=false;
if (year%100==0 && year%400==0) isLeapYear=true;
initMonths(); //為了體現聯動的效果,這裡沒選擇一次年份都初始化一次月份
}
catch(e){;}
}
function initMonths() {
oMonths.length=1;
for (var i=1;i<13;i++) //月份是1~12月
{
var o=new Option(i.toString(),i.toString());
oMonths.add(o);
}
}
function chgMonth() {
try
{
var month=this.options[this.selectedIndex].value;
if (month!='')
{
var days;
if (month.replace(/(1|3|5|7|8|10|12)/ig,'')=='') //判斷是否為大月
days=31;
else if (month.replace(/(4|6|9|11)/ig,'')=='') //判斷是否為小月
days=30;
else if (month=='2' && isLeapYear) //判斷當是2月時,是否為閏月
days=29;
else
days=28;
initDays(days);
}
}
catch(e) {;}
}
function initDays(days) {
oDays.length=1;
for (var i=1;i<=parseInt(days);i++) //迴圈顯示天數
{
var o=new Option(i.toString(),i.toString());
oDays.add(o);
}
}
function chgDay() {
//改變日期時,調用該函數
try
{
var year=oYears.options[oYears.selectedIndex].value;
var month=oMonths.options[oMonths.selectedIndex].value;
var day=this.options[this.selectedIndex].value;
alert('您選擇了'+year+'年'+month+'月'+day+'日');
}
catch(e) {;}
}
</script>
</head>
<body>
<div>
<select id="years">
<option value="">選擇年份</option>
</select>
<select id="months">
<option value="">選擇月份</option>
</select>
<select id="days">
<option value="">選擇日子</option>
</select>
</div>
</body>
</html>