如何使jQuery插件函数可调用以供独立使用,而不在集合上操作

How to make a jQuery plugin function callable for stand-alone use, that does not operate on a collection

本文关键字:操作 集合 独立 插件 jQuery 何使 函数 调用      更新时间:2023-09-26

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

有什么好的建议吗?

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

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