6

我阅读了插件创作的 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 ();

如果$.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 ()为了简单起见,我在这里省略了一些参数)。

有什么好的建议吗?

4

1 回答 1

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 );

这里唯一的区别是$.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();
于 2012-09-14T07:20:22.117 回答