0

プラグイン内の連鎖関数の 1 つにアクセスするにはどうすればよいですか?

これは私のプラグインで、ドキュメントに追加された要素を返す必要があります。

(function($){

        $.fn.extend({ 

            selection: function(options) {

                var defaults = {
                    element:     "selection"
                }

                var options =  $.extend(defaults, options);
                var o = options;

                var $this = this;


               $this.function_1 = function(object)
                {
                    alert('function 1');

                }

                $this.function_2 = function(object)
                {
                    alert('function 2');
                }

                $(document.body).append("<div class='element'>Loading</div>");

                var element = $('.element');

                return element;

            }
        });

    })(jQuery);​

ボタンがクリックされたときに「機能 2」を警告する必要がありますが、Firefox ではエラーが返されます。

以下は私のjsfiddleです、

http://jsfiddle.net/dm3ft/

4

2 に答える 2

1

1 つの方法は、プラグイン関数に引数を追加して、メソッドを文字列として渡すことです。基本は、jQuery プラグイン オーサリング ドキュメントから取得されます。

(function($) {

    var methods = {
        function_1: function(object) {
            alert('function 1');
        },
        function_2: function(object) {
            alert('function 2');
        }
    };


$.fn.selection = function(method, options) {

    return this.each(function(){

        $(this).click(function() {

              // Method calling logic
               if (methods[method]) {
                   return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
               } else if (typeof method === 'object' || !method) {
                   return methods.init.apply(this, arguments);
               } else {
                   $.error('Method ' + method + ' does not exist on jQuery.tooltip');
               }
          });
    });

})(jQuery);

次に、プラグイン メソッドを呼び出します。

  $('.chain-function').selection('function_2'/* optional options object*/);

デモ: http://jsfiddle.net/dm3ft/1/

注:プラグイン関数の内部は DOM 要素であり、クラスの一部であるthisと混同しないことが重要です。this

于 2012-12-22T20:22:58.850 に答える
0

jQuery.fnも使用できます

$(document).ready(function(){

   $('.chain-function').function_2();

});

(function($){

    $.fn.function_2 = function(object){

        alert("yay!");
        var element = $("<div />").addClass("element").text("Loading");
        element.appendTo(  $(document.body) );
        return element;

    };

})(jQuery);​
于 2012-12-22T20:09:02.577 に答える