周選擇器的實現
阿新 • • 發佈:2019-01-02
樓主用了比較質樸的方式實現:easyUI-combobox下拉框。暫時還沒有能力寫成控制元件的形式。
在寫程式碼之前自己寫一個手動格式化時間的方法,為我們的程式碼做鋪墊:
然後初始化這個初始化方法,傳入定義好的id,和需要的年份:Date.prototype.Format = function(fmt) { var o = { "M+" : this.getMonth()+1, //月份 "d+" : this.getDate(), //日 "h+" : this.getHours(), //小時 "m+" : this.getMinutes(), //分 "s+" : this.getSeconds(), //秒 "q+" : Math.floor((this.getMonth()+3)/3), //季度 "S" : this.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o) if(new RegExp("("+ k +")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); return fmt; }
</pre><pre name="code" class="html">function initWeek(year,id){ var currentYear = year; var thisyearbeginday = new Date(currentYear,0,1); var thisyearendday = new Date(currentYear,11,31); var thisWeekBegin = new Date(); var thisWeekEnd = new Date(); if(thisyearbeginday.getDay() == 0){ thisyearbeginday.setDate(thisyearbeginday.getDate()+1); }else if(thisyearbeginday.getDay() != 1){ thisyearbeginday.setDate(thisyearbeginday.getDate() + 8 - thisyearbeginday.getDay()); } thisWeekBegin = thisyearbeginday; if(thisyearendday.getDay() != 0){ thisyearendday.setDate(thisyearendday.getDate() + 7 - thisyearendday.getDay()); } thisWeekEnd = thisyearendday; //alert(thisWeekBegin.getDate()+"年頭周"); //alert(thisWeekEnd.getDate()+"年尾周"); var week1Obj = $("#"+id); var weekHtml = ""; var myweek = 1; var nowweekValue = 0; //迴圈迭代出所需的週數 var json = []; while(thisWeekBegin.getTime() <= thisWeekEnd.getTime()){ var beginTimes = thisWeekBegin.getTime(); var begin = thisWeekBegin.Format("yyyy-MM-dd"); thisWeekBegin.setDate(thisWeekBegin.getDate()+6); var end = thisWeekBegin.Format("yyyy-MM-dd"); var todayTimes = new Date().getTime(); thisWeekBegin.setDate(thisWeekBegin.getDate()+1); var endTimes = thisWeekBegin.getTime(); if(todayTimes>=beginTimes&&todayTimes<=endTimes){ nowweekValue = myweek; } json.push({"id":myweek,"text":myweek+"("+begin+"~"+end+")"}); myweek++; } $("#"+id).combobox({ valueField: 'id', textField: 'text', value:"", height: 30, width:190, panelHeight: json.length >= 7 ? "135px" : "auto"}).combobox("loadData", json); if(nowweekValue >= 2){ $("#"+id).combobox("setValue",nowweekValue-1); } }
在jsp中程式碼:
<select id="weeknum"></select>
效果圖:注:我這裡的周是從一年開始的第一個週一開始算的到最後一個週一的結尾,也就是說可能最後一週回橫跨兩年,不要吃驚。還有這裡用了easyUI的,所以使用的時候需要引入easyui,當然你不想用easyui那就修改原始碼了,原始碼看起來也應該不會很難。有問題請諮詢我:[email protected]