我正在写一个日期选择器插件。我知道那里有很多这样的插件,但是因为在不久的将来会有一些特殊需求,我认为最好编写自己的解决方案。
代码非常简单直接,但我认为我做错了,因为在我将日历向左移动几次后,它开始变得非常慢。
(function ($) {
var defaults = {
single: false,
start: new Date()
};
var methods = {
init: function (options) {
var configs = $.extend(defaults, options);
var calendar = $(this[0]);
calendar.html(build_calendar(configs.single, configs.start));
var date = new Date(configs.start);
date.setDate(1);
date.setMonth(date.getMonth() - 1);
$("#acalendar_left").live("click", function (e) {
e.preventDefault();
calendar.calendar({ single: configs.single, start: date });
});
}
};
$.fn.calendar = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === "object" || !method) {
return methods.init.apply(this, arguments);
} else {
$.error("Method " + method + " does not exist on jQuery.calendar");
}
};
var build_calendar = function (single, start) {
var html = "";
html += "<table>";
html += "<tr>";
html += "<td>";
html += "<a href=\"#\" id=\"acalendar_left\">L</a>";
html += "</td>";
if (single) {
html += "<td>" + build_month(start.getFullYear(), start.getMonth()) + "</td>";
} else {
for (var i = -1; i < 2; i++) {
var date = new Date(start);
date.setDate(1);
date.setMonth(date.getMonth() + i);
html += "<td>" + build_month(date.getFullYear(), date.getMonth()) + "</td>";
}
}
html += "<td>";
html += "<a href=\"#\" id=\"acalendar_right\">R</a>";
html += "</td>";
html += "</tr>";
html += "</table>";
return html;
};
var build_month = function (year, month) {
var months = ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"];
var size = (new Date(year, month + 1, 0)).getDate();
var row = "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td></tr>";
var temporary = row;
var html = "";
html += "<table>";
html += "<tr><td colspan=\"7\">" + months[month] + " " + year + "</td></tr>";
html += "<tr><td>D</td><td>S</td><td>T</td><td>Q</td><td>Q</td><td>S</td><td>S</td></tr>";
for (var i = 0; i < size; i++) {
var date = new Date(year, month, i + 1);
if (date.getDay() == 0 && i > 0) {
html += temporary;
temporary = row;
}
temporary = temporary.replace("{" + date.getDay() + "}", date.getDate());
if (i + 1 == size) {
html += temporary;
}
}
html += "</table>";
html = html.replace(new RegExp("{[0-9]}", "g"), "");
return html;
};
})(jQuery);
$(document).ready(function () {
$("#dcalendar").calendar();
});