2011-11-02 51 views
0

給下面的jQuery插件調用的方法函數:從jQuery插件

(function($) { 

    $.fn.prefCookie = function(method) { 

    var options = { 
     cookieName : 'prefs', 
     actionType : 'click', 
     key : '', 
     value : false 
    } 

    var $obj; 

    var methods = { 

     init : function(config) { 
     return this.each(function() { 
      if(config) { $.extend(options, config) } 
      $obj = $(this); 
      options.value ? 
      $obj.bind(options.actionType,helpers.setPref) : 
      $obj.bind(options.actionType,helpers.togglePref) ; 
     }); 
     }, 

     anotherFunction : function() { 
     console.log('you did it!'); 
     } 

    } 

    var helpers = { 

     togglePref : function() { 

     }, 

     setPref : function() { 

     } 

    } 

    if (methods[method] && method.toLowerCase() != 'init') { 
     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 in the Pref Cookie plugin!'); 
    } 

    } 

})(jQuery); 

怎能不anotherFunction插件安裝到任何東西。我想做$.prefCookie.anotherFunction什麼的,但它不起作用。有什麼建議麼?

+0

_「如果沒有將插件附加到任何東西,怎麼能'anotherFunction'」_不是一個問題......它甚至不是一個完整的句子。 – Sparky

回答

0

看起來您已將其設置爲處理通過字符串傳遞的方法調用。

如果你想這樣做,你說$.prefCookie.anotherFunction(這是不同的,因爲有與之關聯的jQuery的集合),你可以試試...

$.fn.prefCookie.anotherFunction = function() { } 

jsFiddle

1

$('your selector').prefCookie('anotherFunction');應該這樣做。

如果您需要將任何參數傳遞給anotherFunction,只需在字符串'anotherFunction'後面添加它們即可。

+0

你甚至可以在沒有選擇器的情況下運行它:'$()。prefCookie('anotherFunction');' – GregL