[英]jQuery custom plugin -how to add a function
I made a simple plugin for jQuery, which sets minDate and maxDate for two given datePickers. 我为jQuery创建了一个简单的插件,该插件为两个给定的datePickers设置minDate和maxDate。 Now i want to extend it and add a function to set dates.
现在,我想扩展它并添加一个函数来设置日期。
JS JS
(function($) {
$.fn.dateRange = function(){
return this.each(function () {
var from, to;
var self = $(this);
var selectedDate;
$("input",this).prop('readonly', true);
from = $('.from',this);
to = $('.to',this);
from.datepicker({
onClose:function( selectedDate ) {
$(this).siblings(".to").datepicker( "option", "minDate", selectedDate );
}
});
to.datepicker({
onClose:function( selectedDate ) {
$(this).siblings(".from").datepicker( "option", "maxDate", selectedDate );
}
});
//add a function
this.setDate = function (f, t) {
from.datepicker("option",{
defaultDate: new Date(f),
maxDate: new Date(t)
}).val(f);
to.datepicker("option",{
defaultDate: new Date(t),
minDate: new Date(f)
}).val(f);
};
});
};
})(jQuery);
$("div.dateRange").dateRange();
//later
$("#label1").dateRange().setDate("07/02/2013","07/06/2013");
console says: Uncaught TypeError: Object [object Object] has no method 'setDate'. 控制台说:Uncaught TypeError:对象[object Object]没有方法'setDate'。 Whats the best way to add more function to the plugin?
向插件添加更多功能的最佳方法是什么?
Here is a jsbin: http://jsbin.com/acovuj/2/edit 这是一个jsbin: http ://jsbin.com/acovuj/2/edit
There are many ways to accomplish this, as pointed out by the many comments. 正如许多评论所指出的,有很多方法可以实现这一目标。
Here's a boilerplate I find simple and easy to understand: 这是一个简单易懂的样板:
;(function($) {
function init(options) {
return this.each(function() {
// your initialization comes here
// ...
});
}
function setDate(date1, date2) {
// your implementation comes here
// ...
}
var methods = {
init: init,
setDate: setDate
};
$.fn.dateRange = 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.datePicker');
}
};
})(jQuery);
In this setup you call the setDate
method like this: 在此设置中,您将像这样调用
setDate
方法:
$("#label1").dateRange("setDate", "07/02/2013", "07/06/2013");
That is, the name of the method setDate
you actually want to call is an argument to dateRange
, you don't call it directly. 也就是说,您实际要调用的
setDate
方法的名称是dateRange
的参数,您不能直接调用它。
I don't remember where I've seen this example, but I've been using this and it works nicely for me. 我不记得在哪里看到过这个示例,但是我一直在使用它,它对我来说很好用。 For a complete but simple example using this technique, here's a jQuery plugin I created a few days ago.
对于使用此技术的完整但简单的示例, 这是我几天前创建的jQuery插件 。 I hope it will help.
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.