在jQuery插件中添加实例方法
我正在创建自己的jQuery插件。以下是我迄今为止编写的代码:在jQuery插件中添加实例方法,jquery,jquery-plugins,Jquery,Jquery Plugins,我正在创建自己的jQuery插件。以下是我迄今为止编写的代码: (function ($) { $.fn.customPlugin.defaults = { x: 'test', y: 'foo' }; $.fn.customPlugin = function (options) { var opt = $.extend({}, $.fn.customPlugin.defaults, options); re
(function ($) {
$.fn.customPlugin.defaults = {
x: 'test',
y: 'foo'
};
$.fn.customPlugin = function (options) {
var opt = $.extend({}, $.fn.customPlugin.defaults, options);
return this.each(function () {
var current = $(this);
//I want to add instance methods
});
};
})(jQuery);
接下来我想在这个插件中添加实例方法。现在,我有两种方法可以做到这一点
一,
二,
请您指导我应该使用哪种方法,或者您是否可以建议我使用比这更好的方法?jQuery不鼓励使用第二种方法,因为它“会使$.fn名称空间变得混乱”,请检查它们的推荐方法您打算如何使用这些函数?您希望插件的用户能够使用它们,还是仅由插件使用?用户只需从外部传递选项,我将在内部使用这些方法,并对页面的html元素执行某些操作。如果您转到此url,请更清楚。请查看最后一段代码,您将看到一个click方法:itemControl.click(function(){var link=$(this);var link……。我只想将click中的代码分离到某个单独的函数,使代码类似于itemControl.click(method1);其中method1将包含该示例中click事件中的代码。不要忘记返回链接性的
this
。我刚刚访问了那里,作者使用了$.fn.hilight.format=function(txt){return''+txt+'';};我从中得到了第二个想法。jQuery不鼓励使用这些:$.fn.myPlugin$.fn.myPluginDelete,$fn.mypluginad,而不是这些,这很好:$.fn.myPlugin$.fn.myPlugin.delete$.fn.myPlugin.add
(function ($) {
$.fn.customPlugin.defaults = {
x: 'test',
y: 'foo'
};
$.fn.customPlugin = function (options) {
var opt = $.extend({}, $.fn.customPlugin.defaults, options);
this.each(function () {
var current = $(this);
function method1() {
//opt will be used here
}
function method2() {
//opt will be used here
}
});
};
})(jQuery);
(function ($) {
$.fn.customPlugin.defaults = {
x: 'test',
y: 'foo'
};
$.fn.customPlugin = function (options) {
var opt = $.extend({}, $.fn.customPlugin.defaults, options);
this.each(function () {
var current = $(this);
$.fn.customPlugin.method1(opt);
$.fn.customPlugin.method2(opt);
});
};
$.fn.customPlugin.method1(opt)
{
//opt will be used here
};
$.fn.customPlugin.method2(opt)
{
//opt will be used here
};
})(jQuery);