如何使函数变量像jquery插件一样被调用

How to make a function variable be called like jquery plugins?

本文关键字:一样 调用 插件 函数 何使 变量 jquery      更新时间:2023-09-26

插件:

(function( $ ){
  $.fn.myplugin = function( options ) {  
    var mymethod = function(){
      // I want to be able to access "this" here ('.element')
      return this; 
    };
    return this.each(function() {        
      // $('.element', this).mymethod(); <- how to do this?
    });
  };
})( jQuery );

我想这样调用我的方法:

$('.element').mymethod();

这可能吗?

基本上,它需要保持链接,这样我就可以进一步调用其他函数。。。

如果您还没有这样做,我强烈建议您查看jQuery插件创作页面。http://docs.jquery.com/Plugins/Authoring

调用特定方法的最佳方法是进行

$( '#foo' ).myPlugin( 'myMethod' );

实现类似目标的方法是这样的,(注意:所有内容都来自jQuery插件创作网站)

( function ( $ ) {
    var methods = {
        init : function( options ) {
            // Init function here
        },
        destroy : function( ) {
            // Teardown function here
        }
    };
    $.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 exist on jQuery.myPlugin' );
}    

};
})( jQuery );

如果你想像jQuery插件一样调用它,你将无法将其添加到jQuery原型($.fn)中。但如果你只想让this引用选择器的jQuery元素,你可以使用apply:

(function( $ ){
  $.fn.myplugin = function( options ) {  
    var mymethod = function(){
      // I want to be able to access "this" here ('.element')
      return this; 
    };
    return this.each(function() {        
      mymethod.apply($('.element', this));
    });
  };
})( jQuery );

关闭时,只要有新的function关键字,就会丢失this关键字。尝试先保存:

(function( $ ){
  $.fn.myplugin = function( options ) {  
    var that = this;
    var mymethod = function(_this, dotElem){
      // I want to be able to access "this" here ('.element')
        that.hide().blah()...
      return this; // this isn't needed as we are going to anyway return `this.each()`
    };
    return this.each(function() {        
        mymethod(this, $('.element' )); <- how to do this?
    });
  };
})( jQuery );

好吧,那么你只需要做:

$.fn.mymethod = function () { ...   return this; }

jQuery将自动将其调用的元素传递为this

但是以这种方式添加大量函数被认为是不好的做法。这就是为什么大多数插件只在$.fn中添加一个函数,并为调用哪个方法使用字符串参数的原因。

更改MyMethod,使其成为的直接扩展

$.fn.mymethod = function() {
   this.hide(); // the .element
   return this; // continue the daisy chain
}
// example usage
$(document).ready(function() {
   $("div").mymethod();
});

更新了x2(有一个打字错误)!

http://jsfiddle.net/MattLo/2TWMV/1/