如今有不少關於日期的插件,可是都是年、月、日以日曆的形式出現,我在項目有需求是日期如下拉框的形式完成。如圖:html
//HTML代碼以下;
<div class="phone_mation"> <div class="weui-cell__hd" id="birth"> <label class="weui-label"><span>* </span>生日</label> <div class="birth-r"> <div class="year"> <select id="date-sel-year" rel="1985" class="cx_nd"></select> </div> <div class="year"> <select id="date-sel-month" rel="10" class="cx_nd"></select> </div> <div class="year"> <select id="date-sel-day" rel="01" class="cx_nd"></select> </div> </div> </div> </div> //須要引入插件: // 出生年月插件 $.date_picker({ YearSelector: "#date-sel-year", MonthSelector: "#date-sel-month", DaySelector: "#date-sel-day" });
插件代碼:在html文件引入這個js文件和jquery文件便可;jquery
(function($){ $.extend({ date_picker: function(options){ var defaults = { YearSelector: "#sel_year", MonthSelector: "#sel_month", DaySelector: "#sel_day", FirstText: "", FirstValue: 0 }; var opts = $.extend({}, defaults, options); var $YearSelector = $(opts.YearSelector); var $MonthSelector = $(opts.MonthSelector); var $DaySelector = $(opts.DaySelector); var FirstText = opts.FirstText; var FirstValue = opts.FirstValue; // 初始化 var str = "<option value=\"" + FirstValue + "\">" + FirstText + "</option>"; $YearSelector.html(str); $MonthSelector.html(str); $DaySelector.html(str); // 年份列表 var yearNow = new Date().getFullYear(); var yearSel = $YearSelector.attr("rel"); for (var i = yearNow; i >= 1900; i--) { var sed = yearSel==i?"selected":""; var yearStr = "<option value=\"" + i + "\" " + sed+">" + i + "</option>"; $YearSelector.append(yearStr); } // 月份列表 var monthSel = $MonthSelector.attr("rel"); for (var i = 1; i <= 12; i++) { var monthStr=null; var sed = monthSel==i?"selected":""; if(i<10){ monthStr="<option value=\"" + i + "\" "+sed+">" + '0' +i + "</option>"; }else{ monthStr = "<option value=\"" + i + "\" "+sed+">" +i + "</option>"; } $MonthSelector.append(monthStr); } // 日列表(僅當選擇了年月) function BuildDay() { if ($YearSelector.val() == 0 || $MonthSelector.val() == 0) { // 未選擇年份或者月份 $DaySelector.html(str); } else { $DaySelector.html(str); var year = parseInt($YearSelector.val()); var month = parseInt($MonthSelector.val()); var dayCount = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: dayCount = 31; break; case 4: case 6: case 9: case 11: dayCount = 30; break; case 2: dayCount = 28; if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) { dayCount = 29; } break; default: break; } var daySel = $DaySelector.attr("rel"); for (var i = 1; i <= dayCount; i++) { var dayStr=null; var sed = daySel==i?"selected":""; if(i<10){ // dayStr = "<option value=\"" + i + "\" "+sed+">" + +'0'+i + "</option>"; dayStr =`<option value=i ${sed}>0${i}</option>` }else{ // dayStr = "<option value=\"" + i + "\" "+sed+">" + i + "</option>"; dayStr =`<option value=i ${sed}>${i}</option>` } $DaySelector.append(dayStr); } } } $MonthSelector.change(function () { BuildDay(); }); $YearSelector.change(function () { BuildDay(); }); if($DaySelector.attr("rel")!=""){ BuildDay(); } } }); })(jQuery);