简体   繁体   English

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

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

Plugin: 插入:

(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 );

I want to call mymethod like this: 我想这样称呼我的方法:

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

Is this possible? 这可能吗?

Basically it needs to keep the chaining so I can further call other functions... 基本上,它需要保持链接,以便我可以进一步调用其他函数...

If you want to call it like a jQuery plugin you will have no way around adding it to the jQuery prototype ($.fn). 如果要像jQuery插件一样调用它,则无法将其添加到jQuery原型($ .fn)中。 But if you just want to have this reference the jQuery element of your selector you can just use apply : 但是,如果你只是想有这样的参考,你可以只用你选择的jQuery的元素应用

(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 );

Close, you just lose the this keyword whenever there's a new function keyword. 结束语,只要有一个新的function关键字,您就只会失去this关键字。 Try saving it first: 尝试先保存它:

(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 );

If you haven't already done so, I would highly recommend checking out the jQuery plugin authoring page. 如果您还没有这样做,我强烈建议您查看jQuery插件的创作页面。 http://docs.jquery.com/Plugins/Authoring http://docs.jquery.com/插件/作者

The best way to call a specific method would be by going 调用特定方法的最佳方法是

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

The way you would achieve something like that would be like this, ( note: all taken from the jQuery plugin authoring site ) 您实现类似目标的方式将是这样的,(注意:全部取自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 );

Alter MyMethod so its a direct extension 更改MyMethod,使其直接扩展

$.fn.mymethod = function() {
   this.hide(); // the .element
   return this; // continue the daisy chain
}

// example usage
$(document).ready(function() {
   $("div").mymethod();
});

Updated x2 (had a typo)! 更新了x2(有错字)!

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

Well, then you'd just do: 好吧,那么您只需执行以下操作:

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

jQuery will automatically pass the element it's called on as this . jQuery将自动传递它作为this调用的元素。

But it's considered bad practice to add lots of functions this way. 但是,以这种方式添加许多功能被认为是不好的做法。 That's why most plugins just add one function to $.fn and take a string argument for which method to call. 这就是为什么大多数插件仅向$.fn添加一个函数并为要调用的方法采用字符串参数的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM