【问题标题】:Calling a method function from a jQuery plugin从 jQuery 插件调用方法函数
【发布时间】:2011-11-02 23:59:37
【问题描述】:

给出以下 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 之类的,但它不起作用。有什么建议吗?

【问题讨论】:

  • anotherFunction 怎么能不附加插件到任何东西。” 不是问题……它甚至不是一个完整的句子。

标签: jquery plugins jquery-plugins


【解决方案1】:

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

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

【讨论】:

  • 你甚至可以在没有选择器的情况下运行它:$().prefCookie('anotherFunction');
【解决方案2】:

看起来你已经设置它来处理通过字符串传入的方法调用了。

如果您想按照$.prefCookie.anotherFunction 的方式进行操作(这是不同的,因为没有与之关联的 jQuery 集合),请尝试类似...

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

jsFiddle.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多