小编典典

如何使用方法创建jQuery插件?

javascript

我正在尝试编写一个jQuery插件,它将为调用它的对象提供其他功能/方法。我在网上阅读的所有教程(过去2个小时内一直在浏览)最多都包含如何添加选项,但不包含其他功能。

这是我想要做的:

//通过调用该div的插件将div格式化为消息容器

$("#mydiv").messagePlugin();
$("#mydiv").messagePlugin().saySomething("hello");

或类似的规定。归结为以下几点:调用插件,然后调用与该插件关联的函数。我似乎找不到找到这种方法的方法,而且我以前见过很多插件都可以这样做。

这是到目前为止我对插件的了解:

jQuery.fn.messagePlugin = function() {
  return this.each(function(){
    alert(this);
  });

  //i tried to do this, but it does not seem to work
  jQuery.fn.messagePlugin.saySomething = function(message){
    $(this).html(message);
  }
};

我该如何实现这样的目标?

谢谢!


2013年11月18日更新:我已更改对Hari以下评论和支持的正确答案。


阅读 317

收藏
2020-05-01

共1个答案

小编典典

根据jQuery插件创作页面(http://docs.jquery.com/Plugins/Authoring),最好不要混淆jQuery和jQuery.fn命名空间。他们建议这种方法:

(function( $ ){

    var methods = {
        init : function(options) {

        },
        show : function( ) {    },// IS
        hide : function( ) {  },// GOOD
        update : function( content ) {  }// !!!
    };

    $.fn.tooltip = function(methodOrOptions) {
        if ( methods[methodOrOptions] ) {
            return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
            // Default to "init"
            return methods.init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.tooltip' );
        }    
    };


})( jQuery );

基本上,您将函数存储在数组中(作用域为包装函数),并检查输入的参数是否为字符串,如果参数为对象(或为null),则返回默认方法(此处为“ init”)。

然后您可以像这样调用方法…

$('div').tooltip(); // calls the init method
$('div').tooltip({  // calls the init method
  foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method

Javascripts“ arguments”变量是所有传递的参数的数组,因此它可以与任意长度的函数参数一起使用。

2020-05-01