Javascript 同时扩展JQuery插件和JQuery
我正在构建一个Jquery插件。我的框架代码如下:Javascript 同时扩展JQuery插件和JQuery,javascript,jquery,Javascript,Jquery,我正在构建一个Jquery插件。我的框架代码如下: (function (window, document, $, undefined) { var methods = { init : function(options){ }, func_1: function(){ }, func_2: function(){ } }; $.fn.myplugin = function
(function (window, document, $, undefined) {
var methods = {
init : function(options){
},
func_1: function(){
},
func_2: function(){
}
};
$.fn.myplugin = function(args){
if ( methods[args] )
{
return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof args === 'object' || ! args )
{
var opts = $.extend({}, $.fn.myplugin.defaults, args);
var new_args = new Array(opts);
return methods.init.apply( this, new_args );
}
else
{
$.error( 'Method ' + args + ' does not exist' );
}
};
$.fn.myplugin.defaults = {
func_1: function(){},
func_2: function(){}
};
}(window, document, jQuery));
$.myplugin.new_func();
我希望扩展这个插件,以便向JQuery添加额外的功能。因此,我希望调用以下函数:
(function (window, document, $, undefined) {
var methods = {
init : function(options){
},
func_1: function(){
},
func_2: function(){
}
};
$.fn.myplugin = function(args){
if ( methods[args] )
{
return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof args === 'object' || ! args )
{
var opts = $.extend({}, $.fn.myplugin.defaults, args);
var new_args = new Array(opts);
return methods.init.apply( this, new_args );
}
else
{
$.error( 'Method ' + args + ' does not exist' );
}
};
$.fn.myplugin.defaults = {
func_1: function(){},
func_2: function(){}
};
}(window, document, jQuery));
$.myplugin.new_func();
我该怎么做?我知道我可能必须使用$。扩展
,但不确定如何操作
提前感谢。美元.fn.myplugin和美元.myplugin的区别在于后者没有任何上下文。因此,您可以使用以下代码定义后者。为了在$.myplugin的结果上使用链接,您只需要返回一个要在其上使用.new_func()方法的对象,例如某个jQuery对象
$.myplugin = function () {
...
return $('body');
};
好的,在研究了一些较旧的JQuery插件(特别是FancyBox 2)之后,我设法找到了一种实现这一点的方法。以下是整个框架代码:
(function (window, document, $, undefined) {
var methods = {
init : function(options){
},
func_1: function(){
},
func_2: function(){
}
};
$.fn.myplugin = function(args){
if ( methods[args] )
{
return methods[ args ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof args === 'object' || ! args )
{
var opts = $.extend({}, $.fn.myplugin.defaults, args);
var new_args = new Array(opts);
return methods.init.apply( this, new_args );
}
else
{
$.error( 'Method ' + args + ' does not exist' );
}
};
$.fn.myplugin.defaults = {
func_1: function(){},
func_2: function(){}
};
//below is the code I added to get the desired functionality
var D = $.myplugin = function(){};
$.extend(D, {
new_func: function(){
//add functionality here
}
});
}(window, document, jQuery));
也可以在方法
对象中定义一个函数(称为new\u func
或其他任何函数),然后使用methods.new\u func()
从下面的新函数中调用它
干杯。你愿意修改插件的代码吗?不愿意$.myplugin=methods;够了吗?@Jarry不,我得把骷髅当回事is@SanderRoesink我知道我可以使用
$().myplugin('method_name')
调用我的方法,但我不想让我的用户群更容易。我真的不想在DOM上使用这个方法,我只想能够像我刚才描述的那样调用它。我已经有了用于DOM操作的$(选择器).myplugin(选项)
。