jQuery年月日选择器是这样的
本篇文章为大家展示了jQuery年月日选择器是这样的,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
我们在编辑用户资料时经常会遇到选择生日选项的问题,今天我给大家介绍如何使用js来实现年月日(生日)选择器,能够准确计算闰年的年月日,方便表单处理。
HTML
生日中的年月日以
年 月 日
加载jQuery库和选择器插件:
jQuery
我们将选择器封装成jQuyer插件的形式,只需使用以下方式调用即可:
$(function () { $.ms_DatePicker({ YearSelector: ".sel_year", MonthSelector: ".sel_month", DaySelector: ".sel_day" }); });
以下是插件的具体代码:
(function($){ $.extend({ ms_DatePicker: 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 = ""; $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 = ""; $YearSelector.append(yearStr); } // 月份列表 var monthSel = $MonthSelector.attr("rel"); for (var i = 1; i <= 12; i++) { var sed = monthSel==i?"selected":""; var monthStr = ""; $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 sed = daySel==i?"selected":""; var dayStr = ""; $DaySelector.append(dayStr); } } } $MonthSelector.change(function () { BuildDay(); }); $YearSelector.change(function () { BuildDay(); }); if($DaySelector.attr("rel")!=""){ BuildDay(); } } // End ms_DatePicker }); })(jQuery);
上述内容就是jQuery年月日选择器是这样的,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。