有年月的下拉框,要求根據當期日期自動生成下拉框,也可以根據指定值生成。(年的下拉框需前5年,後10年)
html文件:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<style type="text/css">
</style>
<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
根據當前日期生成:<br><select class="year" value=""></select>
<select class="month" value=""></select><br>
自己指定:<br><select class="year" value="2015"></select>
<select class="month" value="7"></select>
</body>
</html>
javascript代碼:
$(function(){
year();
month();
});
/**
* 根據指定value值或當前日期生成年select框
* <select class="year" value=""></select>
* value不給或空字符串時,將根據當前日期生成
*/
function year(){
var sele = document.getElementsByTagName("select");
var year;
var option;
var value;
for (var i=0; i<sele.length; i++) {
if (sele[i].getAttribute("class") == "year") {//對於固有屬性,也可以.屬性名,由於class屬性同時是關鍵字,需要.className 方式使用
//此處需getAttribute(屬性名)方法,不能用.屬性名的方式,firefox和chrome不兼容.value方式,IE可以
value=sele[i].getAttribute("value");
if(value && /^\d+$/.test(value)){
year=parseInt(value);
}else{
year=new Date().getFullYear();
}
for(var j=year-5;j<year+10;j++){
//option創建方式還有var option=new Option('text','value');但IE不支持,firefox和chrome均可
option=document.createElement("option");
option.value=j;
option.innerHTML=j;
if(j==year){
option.selected="selected";
}
//此處需要appendChild()方法
//對於innerHTML='<option></option>'方式IE不支持,firefox和chrome均可
sele[i].appendChild(option);
}
}
}
}
/**
* 根據指定value值或當前日期生成年select框
* <select class="month" value=""></select>
* value不給或空字符串時,將根據當前日期生成
*/
function month(){
var sele = document.getElementsByTagName("select");
var month;
var option;
var value;
for (var i=0; i<sele.length; i++) {
if (sele[i].getAttribute("class") == "month") {
value=sele[i].getAttribute("value");
if(value && /^\d+$/.test(value)){
month=parseInt(value);
}else{
month=new Date().getMonth()+1;
}
for(var j=1;j<=12;j++){
option=document.createElement("option");
if(j<10){
option.value="0"+j;
option.innerHTML="0"+j;
}else{
option.value=j;
option.innerHTML=j;
}
if(j==month){
option.selected="selected";
}
sele[i].appendChild(option);
}
}
}
}
效果圖如下: