Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.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 - Fatal编程技术网

无法在简单jquery插件中调用函数

无法在简单jquery插件中调用函数,jquery,plugins,Jquery,Plugins,我试图在一个简单的jquery插件中调用一个函数。我看到init方法将宽度增加了30,但是add50方法抛出错误uncaughttypeerror:Object[Object Object]没有方法“add50”。不确定发生此错误的原因 jsfiddle: HTML: 尝试添加如下内容: function Plugin( element, options ) { this.element = element; this.options = $.extend( {}, defaul

我试图在一个简单的jquery插件中调用一个函数。我看到init方法将宽度增加了30,但是add50方法抛出错误
uncaughttypeerror:Object[Object Object]没有方法“add50”
。不确定发生此错误的原因

jsfiddle:

HTML:


尝试添加如下内容:

function Plugin( element, options ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options) ;
    this._defaults = defaults;
    this._name = pluginName;
    if (this[options]){
        this[options](this.element);
    } else {
        this.init(this.element);
    }
}
然后你可以像这样使用你所有的插件:
$('#metal').Extender('add50')
并将方法作为选项传入。 我更新了你的小提琴:


当您在
$.fn.plugin
中返回
this
时,它是带有选择器的元素,而不是函数本身。有很多关于插件创作的资源。例如,在jQueryy文档主菜单中。也可以在谷歌上搜索…很多教程太棒了,你能解释一下你所做的改变吗?返回对象而不是
this.each({})太棒了,这也行-你能详细说明我遗漏了什么吗?这将帮助我理解构建基本插件的灰色地带。我并不是这样写插件的——但我所做的只是添加一个if/else检查,看看传递的选项是否匹配任何可用的方法
this[options]
this.add50
相同。如果找到任何匹配项,我们将调用该方法,否则返回正常初始化。
<div id='metal'></div>
#metal{
    width: 50px;
    height: 10px;
    background:red;
}
function Plugin( element, options ) {
    this.element = element;
    this.options = $.extend( {}, defaults, options) ;
    this._defaults = defaults;
    this._name = pluginName;
    if (this[options]){
        this[options](this.element);
    } else {
        this.init(this.element);
    }
}
;(function ( $, window, document, undefined ) {

    // Create the defaults once
    var pluginName = 'Extender',
        defaults = {
            propertyName: "value"
        };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options) ;
        this._defaults = defaults;
        this._name = pluginName;
        this.init();
    }

    Plugin.prototype = {
        init : function () {
           // console.log($(this.element).width());
           $(this.element).width($(this.element).width() + 30);
        },
        add50 : function(){
           $(this.element).width($(this.element).width() + 50);
        }

     };

    $.fn[pluginName] = function ( options ) {
        return $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
    }

})( jQuery, window, document );

$('#metal').Extender().add50();