Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

javascript - Calling a jQuery plugin without specifying any elements

Say I have the following jQuery plugin:

$.fn.myPlugin = function () {
    //plugin code
}

Normally, you call a plugin on a certain number of elements, like such:

$("body").myPlugin();

Is there any way I can call my plugin without specifying an element?

I have tried calling it like such: $.myPlugin();, but that does not work.

What works is this: $().myPlugin();, but is that the correct way to invoke it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The quick way to write it is this:

$.myPlugin = function () {
    // Plugin code
}

The right way to write it is this:

(function ($) {
    $.extend({
        myPlugin: function () {
            // plugin code
        }
    });
})(jQuery);

It might seem a little confusing at first, but it's a common jQuery pattern.

(function($){
     // Code
})(jQuery);

This code creates an anonymous function and calls it passing jQuery as argument. Inside the function this argument is bound to $. The reason this is done it that it allows you to work with the $ even if jQuery is running in no-conflict mode.

The second part is $.extend. It basically extends the jQuery object itself, when called with a single argument.

Calling the plugin (in the quick and the right case) is:

$.myPlugin();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...