您的位置:首页 > Web前端 > JavaScript

js显示年月日(润年2月29天)

2014-09-11 10:00 106 查看
代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>  </title>
<meta name="generator" content="editplus" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<style type="text/css">
select{ width:100px;}
span{ padding:0 10px 0 5px;}
</style>
</head>
<body>
<select id="year" name="">

</select><span>年</span>
<select id="month" name="">

</select><span>月</span>
<select id="day" name="">

</select><span>日</span>

<p>[1,3,5,7,8,10,12]共31天</p>
<p>[4,6,9,11]共30天</p>
<p>[2]共28天</p>
<p>润年: [2]共29天</p>
<script type="text/javascript">
window.onload = function()
{
var year = $('year');
var month = $('month');
var day = $('day');

getDate(year,1980,(new Date).getFullYear());
getDate(month,1,12);
getDate(day,1,31);
month.onchange = function()//改变月份值的时候
{
var val = this.value; //获得月份的值
var valY = year.value; //获得年的值
var run = (valY % 4 == 0 && valY % 100 != 0) || ( valY % 400 == 0)//判断是不是润年
removeDate(day)//清空日的值
if(val == 2){//如果是2月
return run ? getDate(day,1,29): getDate(day,1,28)//在如果是2月的前提下如果是润年则一个月有29年,否则为28天
}else if(val == 4 || val == 6 || val == 9 || val == 11){ //如果是一个月30天的月份
getDate(day,1,30); //一个月有30天
}else{
getDate(day,1,31); //则剩下的每个月都为31天
}
}
year.onchange = function()//改变年份值的时候
{
var val = this.value;//当前年份的值
var valM = month.value; //当前月份的值
var run = (val % 4 == 0 && val % 100 != 0) || ( val % 400 == 0)//判断是不是润年
removeDate(day);//清空日的值
if(run && valM == 2){//如果选中的年份是润年并且是2份
getDate(day,1,29) //则当月有29天
}else if(valM ==2){ //如果选中的年份不是润年但月份是2月
getDate(day,1,28)//则当月有28天
}else if(valM == 4 || valM == 6 || valM == 9 || valM == 11){ //如果是一个月30天的月份
getDate(day,1,30);//一个月有30天
}else{
getDate(day,1,31);//则剩下的每个月都为31天
}
}

}
function $(id)
{
return typeof id === 'string' ? document.getElementById(id) : id;
}
function getDate(obj,m,n)
{
for( var i = m; i <= n; i++)
{
var option = document.createElement('option'); //创建option

option.value = i; //设置option的值

option.innerHTML = i; //设置option的innerHTML;

obj.appendChild(option); //将option添加入对象中
}
}
function removeDate(obj)
{
obj.options.length = 0; //清空对象中的option
}
</script>
</body>
</html>


运行效果如下:



====
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: