jQuery UI Datepicker с подвыпившим jQuery

Какие-либо идеи, как реализовать подвыпившие подсказки по UI jQuery Datepicker? В основном я хочу получить подсказку, когда пользователь перемещается в определенную дату в Datepicker. Datepicker будет отображен встроенный и всегда видимый.

Спасибо!

7
задан remedix 19 February 2010 в 22:38
поделиться

1 ответ

Звучит довольно круто,

Вот мое решение. Прочитайте комментарии.

(function($){


/** 
 * Returns a dictionary, where the keys are the day of the month, 
 * and the value is the text.
 * @param year - The year of the events.
 * @param month - The month of the events.
 * @param calendarID - Events for a specific calendar.
 */
function getMonthEvents(year, month, calendarId){
  return {11: "My birthday.", 23: "My anniversary" };
}

// Receives January->1
function addTipsys(year, month, calendarId){
   var theEvents = getMonthEvents(year, month, calendarId);
   var theDateLinks = $('#' + calendarId + ' .ui-datepicker-calendar a');
   for(eventDay in theEvents){
      // Minus one, because the date in the tipies are regular dates (1-31)
      // and the links are 0-based.
      theDateLinks.eq(eventDay-1)  // select the right link
         .attr('original-title', theEvents[eventDay])  // set the text
         .tipsy();   // init the tipsy, set your properties.
   }
}

// Because the the event `onChangeMonthYear` get's called before updating 
// the items, we'll add our code after the elements get rebuilt. We will hook 
// to the `_updateDatepicker` method in the `Datepicker`.
// Saves the original function.
var _updateDatepicker_o = $.datepicker._updateDatepicker;
// Replaces the function.
$.datepicker._updateDatepicker = function(inst){ 
   // First we call the original function from the appropiate context.
   _updateDatepicker_o.apply(this, [inst]); 
   // No we can update the Tipsys.
   addTipsys(inst.drawYear, inst.drawMonth+1, inst.id);
};

// Finally the calendar initializer.
$(function(){
   // Creates the date picker, with your options.
   $("#datepicker").datepicker();
   // Gets the date and initializes the first round of tipsies.
   var currentDate = $('#datepicker').datepicker('getDate');
   // month+1 because the event considers January->1
   // Last element is null, because, it doesn't actualy get used in the hanlder.
   addTipsys(currentDate.getYear(), currentDate.getMonth()+1, 'datepicker');
});

})(jQuery);

Неудобства:

  1. Метод _updateDatepicker вызывается также, когда пользователь выбирает день из видимого месяца, или когда вы устанавливаете дату через datepicker('setDate', theDate), что может быть немного неэффективно.

  2. Он полагается на частную функцию Datepicker, если в будущих версиях они решат изменить его функциональность или изменить название, этот код сломается. Хотя из-за характера функции я не думаю, что это произойдет в ближайшее время.

NOTE: Мой первый подход заключался в подключении к событию onChangeMonthYear события ui.datepicker, но поскольку событие срабатывает перед заменой дат в календаре, метод addTipsys добавил бы tipsy's к датам календаря, которые скоро будут очищены. Поэтому необходимо вызвать событие addTipsys ПОСЛЕ того, как элементы обновятся.

ПРОСТОЙ ХАК: Подключите метод к событию onChangeMonthYear вашего календаря и сделайте setTimeout для вызова tipy's. Необходимо будет выполнить некоторую валидацию.

5
ответ дан 7 December 2019 в 12:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: