[英]Calling a function in a jquery plugin
我正在尝试获取正在使用的jquery插件的对象。 我希望最终能够为插件添加功能以满足我的需求。 我目前在调用插件中定义的函数时遇到问题。这是我拥有的代码的骨架:
;(function($) {
$.fn.myPlugin = function(o) {
.//Implementations here
.
.
var Ex = function(e){
//implementations here
};
};
})(jQuery);
我想要此函数的原因是因为我想访问定义的一些变量。 我希望能够从我的html文件中调用函数Ex,但是到目前为止我所做的任何尝试都没有用。 我尝试过的一个例子是:
$.fn.myPlugin.Ex("x");
任何地方都没有返回声明。 我不太擅长javascript或jquery,但我想学习。 感谢您在解释我做错事情方面的任何帮助。
您的插件设计模式错误。
要实现您想要的目标,可以使用以下通用选项:
;(function($){
var methods = {
init: function() {
//stuff
},
function1: function() {
//stuff
},
function2: function(opt) {
//stuff
}
};
$.fn.myPlugin= 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);
}
};
})(jQuery);
具有这种结构:
$.fn.myPlugin();
将调用init()
$.fn.myPlugin("function1");
将调用function1()
$.fn.myPlugin("function2",option_exemple);
将调用function2(opt)
免责声明:我经常使用它,但这不是我的。 不记得我在哪里找到*。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.