我读了jquery documentation of plugin authoring并且对此很熟悉。但是,给出的示例总是对一组先前匹配的元素进行操作。我想创建一个可以同时执行这两项操作的函数:
// example usage of my to-be-created plugin function
// this is the way described in the docs, and I know how to do that
$("a").myFunction ()
// but I also want to be able to call the function without a collection:
$.myFunction ();
如果调用 $.myFunction ()
时没有要操作的集合,它将创建自己的要匹配的元素集合 - 一种初始化过程(但不一定只运行一次) .此外,$.myFunction ()
应保持可链接性。
我要实现的伪代码:
// [...]
function myFunction (): {
if (notCalledOnACollection) {
// this should run when called via $.myFunction ()
$elements = $("a.myClass");
}
else {
$elements = $(this);
}
return $elements.each (function () {
// do sth. here
});
}
我真的很想将所有函数实现/功能保留在一个函数定义中,而不是在 jQuery 对象的两个不同位置有两个单独命名的函数或两个同名函数。
当然我可以添加一个参数 myFunction (do_init)
来指示要执行 if
语句的哪个分支,但这会使我的参数列表变得困惑(我想将这种方法用于多个插件,并且会有对 myFunction ()
的争论,为了简单起见,我在这里省略了这些争论。
有什么好的建议吗?
最佳答案
只需在插件定义中添加另一个引用,即可轻松使用标准插件代码:
(function( $ ) {
$.myPlugin = $.fn.myPlugin = function(myPluginArguments) {
if(this.jquery)
//"this" is a jquery collection, do jquery stuff with it
} else {
//"this" is not a jquery collection
}
};
$.fn.myPlugin.otherFunc = function() {
};
})( jQuery );
这里唯一的区别是 $.myPlugin =
部分,它允许您直接调用您的插件而无需运行 jquery 的选择器函数。如果您决定需要其他功能或属性,您可以将它们创建为插件的属性。
用法:
//using a selector (arguments optional)
$(".someClass").myPlugin();
//using the options variable - or whatever your arguments are
$.myPlugin({id: "someId"});
//accessing your other functions/properties
$.myPlugin.otherFunc();
关于javascript - 如何使不对集合进行操作的 jQuery 插件函数可调用以供独立使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12419658/