自定义属性的应用:日期下拉框的生成

来源:互联网 发布:服装销售软件破解版 编辑:程序博客网 时间:2024/05/17 04:34

有年月的下拉框,要求根据当期日期自动生成下拉框,也可以根据指定值生成。(年的下拉框需前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);     }      }    }}

效果图如下:


原创粉丝点击