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

发布于 2024-12-28 12:40:40 字数 478 浏览 1 评论 0原文

插件:

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

我想这样调用 mymethod:

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

这可能吗?

基本上它需要保持链接,以便我可以进一步调用其他函数......

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不可一世的女人 2025-01-04 12:40:40

如果您还没有这样做,我强烈建议您查看 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 );

If you haven't already done so, I would highly recommend checking out the jQuery plugin authoring page. http://docs.jquery.com/Plugins/Authoring

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 )

( 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 );
南七夏 2025-01-04 12:40:40

如果您想像 jQuery 插件一样调用它,您将无法将其添加到 jQuery 原型 ($.fn)。但是,如果您只想让 this 引用选择器的 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 );

If you want to call it like a jQuery plugin you will have no way around adding it to the jQuery prototype ($.fn). But if you just want to have this reference the jQuery element of your selector you can just use 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 );
如梦 2025-01-04 12:40:40

关闭,只要有新的 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 );

Close, you just lose the this keyword whenever there's a new function keyword. 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 );
猥琐帝 2025-01-04 12:40:40

好吧,那么您只需这样做:

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

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

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

Well, then you'd just do:

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

jQuery will automatically pass the element it's called on as 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.

余生共白头 2025-01-04 12:40:40

更改 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/

Alter MyMethod so its a direct extension

$.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)!

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文