<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>级联选择日期</title>
<script type="text/javascript">
onload = function() { // 页面加载后就生成年和月
generateYear();
generateMonth();
}
function generateYear() {
var yearSelect = document.getElementById("yearSelect");
var currentYear = new Date().getFullYear();
for (var x = currentYear; x >= currentYear - 200; x--) {
var option = document.createElement("option");
option.innerHTML = x;
option.value = x;
yearSelect.appendChild(option);
}
}
function generateMonth() {
var monthSelect = document.getElementById("monthSelect"); // 获取到月份的下拉列表
for (var x = 1; x <= 12; x++) { // 循环12次
var option = document.createElement("option");
option.innerHTML = x;
option.value = x;
monthSelect.appendChild(option); // 每次创建一个option添加到下拉列表中
}
}
function generateDate() { // 如果选了年和月, 就生成日期
var dateSelect = document.getElementById("dateSelect"); // 获取日期下拉列表
var optionArr = dateSelect.options; // 获取所有子级option, 类似dateSelect.childNodes, 但不包含Text
optionArr.length = 1; // 修改数组的长度, 多余的会被删掉
/*
for (var x = 1; x < optionArr.length; x++) // 循环遍历
dateSelect.removeChild(optionArr[x--]); // 删除每一个
*/
var year = document.getElementById("yearSelect").value;
var month = document.getElementById("monthSelect").value;
if (year == "" || month == "")
return;
var days;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
days = 31; // 1,3,5,7,8,10,12月份是31天
else if (month == 2)
days = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 ? 29 : 28; // 判断是否闰年
else
days = 30; // 其他月份是30天
for (var x = 1; x <= days; x++) {
var option = document.createElement("option");
option.innerHTML = x;
option.value = x;
dateSelect.appendChild(option);
}
}
</script>
</head>
<body>
<select id="yearSelect" onchange="generateDate();"><option value="">-请选择年份-</option></select>
<select id="monthSelect" onchange="generateDate();"><option value="">-请选择月份-</option></select>
<select id="dateSelect"><option value="">-请选择日期-</option></select>
</body>
</html>
//看下这个吧,老师写的,希望能帮到你
|