从jQuery插件调用方法函数

时间:2011-11-02 23:59:37

标签: jquery plugins jquery-plugins

提供以下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或其他什么,但它不起作用。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

$('your selector').prefCookie('anotherFunction');应该这样做。

如果您需要将任何参数传递给anotherFunction,只需在字符串'anotherFunction'之后添加它们。

答案 1 :(得分:0)

看起来你已将其设置为处理由字符串传入的方法调用。

如果你想像$.prefCookie.anotherFunction那样做(因为没有与之关联的jQuery集合,这是不同的),尝试类似......

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

jsFiddle