将回调添加到jQuery DatePicker的正确方法 [英] Proper way to add a callback to jQuery DatePicker
问题描述
DatePicker有一个内部函数, _adjustDate()
,我想在之后添加一个回调。
DatePicker has an internal function, _adjustDate()
, which I'd like to add a callback after.
这就是我目前的做法。基本上,只需用自身替换功能定义,再加上新操作。这会影响所有日期选择器,我也不确定是否需要。
This is how I'm currently doing this. Basically, just replacing the function defintion with itself, plus the new operations. This effects all datepickers, which I'm not sure is desired, either.
$(function(){
var old = $.datepicker._adjustdate;
$.datepicker._adjustDate = function(){
old.apply(this, arguments);
// custom callback here
console.log('callback');
};
});
_adjustDate是在下一个/上个月点击期间调用的内容。该函数有三个参数。我很好奇是否有更好的方法来添加回调。
_adjustDate is what's called during the next/prev month clicks. The function takes three parameters. I'm curious if there's a better way to add the callback.
我希望最终结果如下所示;其中 afterAjustDate
是回调句柄:
I'd like to have the end result look like this; where afterAjustDate
is the callback handle:
$('#datepicker').datepicker({
showButtonPanel: true
, afterAdjustDate: function(){ $(this).find('foo').addClass('bar'); }
});
onChangeMonthYear
不是可接受的事件替代方案, live()
/ delegate()
(在IE中不起作用)绑定选项。
onChangeMonthYear
is not an acceptable event alternative, neither are the live()
/delegate()
(don't work in IE) binding options.
这来自于选择月份后应用类/操作元素的需要。更改月份会重新创建日历中的元素;执行此操作时,jQueryUI不够智能,无法继承类更改。因此,我需要在更改日期后进行回调。
This comes from the need of applying classes/manipulating elements after the month is selected. Changing the month recreates elements in the calendar; when this is performed jQueryUI is not smart enough to inherit the class changes. Thus, I need a callback after changing the date.
推荐答案
我写了一个小型演示来做到这一点......
I wrote a small demo that does this...
我创建了一个包含$ .datepicker扩展名的对象文字,然后在$ .datepicker和我的对象上执行$ .extend。
I create an object literal that contains the extensions to $.datepicker and then do $.extend on $.datepicker and my object.
您可以在此处查看: http://jsfiddle.net/NHN4g/4/
这是扩展本身:
(function($){
var datepickerExtensions = {
_oldAdjustDate: $.datepicker._adjustDate,
_adjustDate: function(id, offset, period) {
var target = $(id);
var inst = this._getInst(target[0]);
var afterAdjustDate = this._get(inst, 'afterAdjustDate');
this._oldAdjustDate(id, offset, period);
if(afterAdjustDate && typeof afterAdjustDate === 'function'){
afterAdjustDate(id, offset, period);
}
}
}
$.extend($.datepicker, datepickerExtensions);
})(jQuery);
以及演示:
(html )
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all">
<div class="demo">
<p>Date: <input type="text" id="datepicker"></p>
</div><!-- End demo -->
(javascript)
(javascript)
var changed = false;
$("#datepicker").datepicker({
afterAdjustDate: function(i,o,p){
if(!changed){
$('.ui-datepicker-month').css('color', '#f00');
}
changed = !changed;
}
});
这篇关于将回调添加到jQuery DatePicker的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!