Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jquery插件的公共调用方法_Jquery_Plugins_Methods_Call_Public - Fatal编程技术网

jquery插件的公共调用方法

jquery插件的公共调用方法,jquery,plugins,methods,call,public,Jquery,Plugins,Methods,Call,Public,我尝试了这个网站上的jQuery插件样板,但是我不能调用公共方法fooBar。 我的意思是: /** * jQuery lightweight plugin boilerplate * Original author: @ajpiano * Further changes, English comments: @addyosmani * More further changes, German translation: @klarstil * Licensed under the MI

我尝试了这个网站上的jQuery插件样板,但是我不能调用公共方法fooBar。 我的意思是:

/**
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, English comments: @addyosmani
 * More further changes, German translation: @klarstil
 * Licensed under the MIT license
 */
;(function ( $, window, document, undefined ) {
    "use strict";

    var pluginName = 'defaultPluginName',
        defaults = {
            propertyName: "value"
        };    

    var privateMethod = function() {
    };

    function Plugin( element, options ) {

        this.element = element;
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();

    }

    Plugin.prototype.init = function () {
    };

    Plugin.prototype.fooBar = function(someValue) {
        var fooBarModifier = 3;

        function privateFooBar(someValue) {
            return someValue * fooBarModifier;
        }

        someValue = privateFooBar(someValue);
        return someValue;
    };

    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName, 
                new Plugin( this, options ));
            }
        });
    }
})( jQuery, window, document );
例如,我使用的插件如下:

$('#wrapper').defaultPluginName();
$('#wrapper').fooBar();
我试着这样调用这个方法:

$('#wrapper').defaultPluginName();
$('#wrapper').fooBar();
但是我的控制台给了bck一个错误:

TypeError:$(…).fooBar不是函数$('#包装器').fooBar()

如何在此选择上调用方法?

这是因为
$(“#wrapper”)
不返回插件的实例,它为匹配的DOM元素集返回一个jQuery包装,而该DOM元素集没有
fooBar
方法

如果要调用插件的public方法,请尝试:

$('#wrapper').data('plugin_defaultPluginName').fooBar();
插件实例作为数据存储到名为
'plugin\uu'+pluginName
的元素中,因此:

  • $(“#包装器”).data('plugin_defaultPluginName')
    将返回名为
    defaultPluginName的插件实例
  • .fooBar()
    调用插件实例中的方法
    fooBar

  • 这是因为
    $(“#包装器”)。
    不返回
    插件的实例
    ,它为匹配的dom元素集返回一个jQuery包装器,该dom元素集不具有
    fooBar
    方法如果我仍然想使用$(“#包装器”).fooBar();调用该方法