javascript如何实现日期选择功能呢?本文介绍了JavaScript日期选择功能实例,亲测可用,希望能够解决大家的问题。
本文实例讲述了JavaScript日期选择功能。分享给大家供大家参考,具体如下:
代码如下 复制代码
<html xmlns="">
<head>
<meta charset="utf-8">
<title>javascript日期选择</title>
<style type="text/css">
option{
width:150px;
}
</style>
</head>
<body>
<!--<input type="hidden"value="window.location.href"/>-->
<br />
<div id="dateOp">
<select id="selectYear"onchange="getDay()"></select>年
<select id="selectMonth"onchange="getDay()"></select>月
<select id="selectDay"></select>日
<input type="button"value="getdate"/>
</div>
<script type="text/javascript">
//或得当前年月日
vardate =newDate();
varyear = date.getFullYear();
varmonth = date.getMonth() + 1;
varday = date.getDate();
varstartYear = 2000;
varendYear = 2050;
varbutton = document.getElementsByTagName("input")[0];
//得到三个select项
varselectYearElement = document.getElementById("selectYear");
varselectMonthElement = document.getElementById("selectMonth");
varselectDayElement = document.getElementById("selectDay");
//selectYearElement.onchange = getDay();
//selectMonthElement.onchange = getDay();
//selectYearElement.addEventListener
getYear();
getMonth();
getDay();
//年份函数
functiongetYear() {
for(vari = startYear; i <= endYear; i++) {
varopYearElement = document.createElement("option");
vartextElement = document.createTextNode(i);
opYearElement.appendChild(textElement);
opYearElement.value = i;
selectYearElement.appendChild(opYearElement);
}
//设置默认年份的值
selectYearElement.selectedIndex = year - startYear;
}
//月份函数
functiongetMonth() {
for(vari = 1; i <= 12; i++) {
varopMonthElement = document.createElement("option");
textMonth = document.createTextNode(i);
opMonthElement.appendChild(textMonth);
opMonthElement.value = i;
selectMonthElement.appendChild(opMonthElement);
}
//设置默认年份的值
selectMonthElement.selectedIndex = month - 1;
}
//日期函数
functiongetDay() {
vargetSelectedYear = selectYearElement.selectedIndex + startYear;
vargetSelectedMonth = selectMonthElement.selectedIndex + 1;
varflag = 0;
varselectDayElement = document.getElementById("selectDay");
if(selectDayElement.hasChildNodes()) {
varoptionElements = selectDayElement.getElementsByTagName("option");
for(vari = 0; i < optionElements.length; i++) {
selectDayElement.removeChild(optionElements[0]);
//不知道为什么必须得自减一
i--;
}
}
else{
}
//得到闰年
if((getSelectedYear % 4 == 0 && getSelectedYear % 100 != 0) || getSelectedYear % 400 == 0) {//得到闰年的年号
//alert("闰年");
//得到闰年大月份除二月以外
if((getSelectedMonth <= 7 && getSelectedMonth % 2 == 1 && getSelectedMonth != 2) || (getSelectedMonth >= 8 && getSelectedMonth % 2 == 0)) {//得到大月
setDay(flag = 31);
}
elseif(getSelectedMonth <= 7 && getSelectedMonth == 2) {
setDay(flag = 29);
}