如何调用jQuery插件的用户定义方法中的元素

时间:2014-03-02 10:31:35

标签: javascript jquery jquery-plugins selector

我有一个jQuery插件,它接受多个元素和一些方法,如:

(function($){

  methods = {
    init : function( options, callbacks) {
      $.fn.myPlugin.settings = $.extend({
        'userDefinedMethod': function() {}
      }, options);

      return this.each(function(){
        $.fn.myPlugin.settings.userDefinedMethod();
      }
    }
  }

  $.fn.myPlugin = function(method) {
    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 exists on jQuery.myPlugin' );
    }
  }

})(jQuery);

一个简单的例子,它可以让你理解我想要实现的目标:

$(document).ready(function(){
  $('#myElement1, #myElement2, #myElement3').myPlugin({
    userDefinedMethod: function() {
      // I want here to use the elements in selector
      $(this).css('color', 'black');
    }
  });
});

我知道上面示例中的$(this)将代表jQuery插件对象,但我想以某种方式使用提供的选择器中的每个元素。

2 个答案:

答案 0 :(得分:1)

$(document).ready(function () {
    $('#myElement1, #myElement2, #myElement3').myPlugin({
        userDefinedMethod: function () {
            // I want here to use the elements in selector
            $(this).css('color', 'red');
        }
    });
});

(function ($) {

    methods = {
        init: function (options, callbacks) {
            //don't set the settings to shared object
            this.settings = $.extend({
                userDefinedMethod: $.noop
            }, options);

            return this.each($.proxy(function (idx, el) {
                //use Function.call() to set a custom execution context
                this.settings.userDefinedMethod.call(el);
            }, this))
        }
    }

    $.fn.myPlugin = function (method) {
        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 exists on jQuery.myPlugin');
        }
    }

})(jQuery);

演示:Fiddle

答案 1 :(得分:1)

methods.init函数this中将是通过查询选择器获得的jQuery对象。因此,如果您要将this发送至userDefinedMethod,请在调用该功能时使用applycall

...
var methods = {
    init : function( options, callbacks) {
      $.fn.myPlugin.settings = $.extend({
        'userDefinedMethod': function() {}
      }, options);

      $.fn.myPlugin.settings.userDefinedMethod.call(this);
      // or if you want to send the arguments
      // $.fn.myPlugin.settings.userDefinedMethod.apply(this, arguments);
      return this;
    }
}
...

另外,请不要忘记您没有使用var声明methodsmethods将成为一个神奇的全球变量...

我还纠正了生成语法错误的缺失)

JSFIDDLE