1

すべてのjQuery関数、メソッド、および使用可能なプロパティを持つjQueryプラグインを作成するための最短かつ最速の方法は何ですか。ただし、ほとんどの場合jquery.*-plugin.jsファイルに保存されるこのパターンを回避するには、次のようにします。

(function($){
    $.yourPluginName = function(el, radius, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Add a reverse reference to the DOM object
        base.$el.data("yourPluginName", base);

        base.init = function(){
            if( typeof( radius ) === "undefined" || radius === null ) radius = "20px";

            base.radius = radius;

            base.options = $.extend({},$.yourPluginName.defaultOptions, options);

            // Put your initialization code here
        };

        // Sample Function, Uncomment to use
        // base.functionName = function(paramaters){
        // 
        // };

        // Run initializer
        base.init();
    };

    $.yourPluginName.defaultOptions = {
        radius: "20px"
    };

    $.fn.yourPluginName = function(radius, options){
        return this.each(function(){
            (new $.yourPluginName(this, radius, options));

           // HAVE YOUR PLUGIN DO STUFF HERE


           // END DOING STUFF

        });
    };

})(jQuery);

main.js私は、JavaScriptロジックとjQueryのすべてを実行するファイルで使用できる簡単なjQueryプラグインパターン/テンプレートを探しています。

私がやりたいjquery.*-plugin.jsのは、私のWebサイトの一部のセクションと部分でのみ使用されるカスタムプラグインの一部にファイルを使用しないようにすることです。

4

1 に答える 1

1

本当に必要な機能によって異なりますが、jQueryプラグインはjQuery.prototype(エイリアス化されたjQuery.fn)のメソッドであるため、次のようにすることができます。

$.fn.myPlugin = function () {
    // `this` refers to the jQuery instance. Put your logic in here.
};

次に、次のように呼び出すことができます。

$(".some-selector").myPlugin();

これが実際のです。

于 2013-03-05T10:32:38.930 に答える