2012-12-22 24 views
0

如何訪問插件中的鏈接函數之一?如何訪問插件中的鏈接函數之一?

這是我的插件,我需要在文檔中返回一個附加元素。

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

當按鈕被點擊但它在Firefox上返回錯誤時,它應該提醒'function 2'。

下面是我的jsffiddle,

http://jsfiddle.net/dm3ft/

回答

1

一種方法是添加一個參數的插件功能來傳遞方法的字符串。基礎知識是從jQuery plugin authoring docs採取:

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

DEMO:http://jsfiddle.net/dm3ft/1/

注意:你意識到this插件功能裏面是DOM是非常重要的元素,而不是將它與this混淆成爲你的類的一部分

+0

謝謝。在我的插件的問題是,沒有'點擊'或每個'事件'... – laukok

+1

'點擊'我明白了......我剛剛使用'點擊'因爲鏈接說「clcik在這裏」。假設你在DOM中有多個元素的選擇器上調用插件,'each'用於循環完整的元素集合。如果你不想'點擊',刪除它,只需使用處理器內的代碼 – charlietfl

+0

'如果集合中只有一個元素,每個'都無所謂(或失敗) – charlietfl

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