如何使jQuery插件函数可以独立使用,不能在集合上运行

Dyn*_*lon 6 javascript jquery plugins jquery-plugins

我阅读了插件创作jquery文档,并熟悉它.但是,给出的示例始终对一组先前匹配的元素进行操作.我想创建一个可以同时执行这两项操作的函数:

// 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 ();
Run Code Online (Sandbox Code Playgroud)

如果$.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 
    });
}
Run Code Online (Sandbox Code Playgroud)

我真的希望将所有函数实现/功能保留在单个函数定义中,并且在jQuery对象中的两个单独位置中没有两个单独命名的函数或两个同名函数.

当然,我可以添加一个参数myFunction (do_init)来指示if要执行的语句的哪个分支,但这会使我的参数列表变得混乱(我希望将这种方法用于多个插件,并且会有一些论证myFunction (),我只是为了简单而省略了).

有什么好建议吗?

Don*_*ghn 8

只需在插件定义中添加另一个引用,您就可以轻松使用标准插件代码:

(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 );
Run Code Online (Sandbox Code Playgroud)

这里唯一的区别是$.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();
Run Code Online (Sandbox Code Playgroud)