为$ .plugin()用法准备插件而不是$(selector).plugin()

jol*_*olt 3 jquery

只是:

(function($){
    $.fn.plugin = function()
    {
        // results in error
        // when called like
        // $.plugin();
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

错误是(从Chrome控制台复制):

Uncaught TypeError: Object function ( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    } has no method 'plugin'
Run Code Online (Sandbox Code Playgroud)

我必须遵循哪些规则才能使我的插件在没有元素选择的情况下工作?

Fel*_*ing 6

只需将功能直接分配给$.plugin:

(function($){
    $.plugin = function()
    {
        // ...
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

当然this不再是指所选元素,而是指jQuery自身.