无法在简单的jquery插件中调用函数 [英] not able to call a function within a simple jquery plugin

查看:97
本文介绍了无法在简单的jquery插件中调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个简单的jquery插件中调用一个函数.我看到init方法将宽度增加了30,但是add50方法抛出了错误Uncaught TypeError: Object [object Object] has no method 'add50'.不知道是什么原因导致此错误发生.

I'm trying to call a function within a simple jquery plugin. I see that the init method adds 30 to the width but the add50 method throws error Uncaught TypeError: Object [object Object] has no method 'add50'. Not sure what is causing this error to occur.

jsfiddle: http://jsfiddle.net/nsshrinivasan/KnDMq/6/

jsfiddle: http://jsfiddle.net/nsshrinivasan/KnDMq/6/

;(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(this.element);
    }

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

     };

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

})( jQuery, window, document );

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

HTML:

<div id='metal'></div>

CSS:

#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);
    }
}

然后,您可以像下面这样使用所有插件:$('#metal').Extender('add50');并将您的方法作为选项传递. jsFiddle更新

Then you can all your plugin like this: $('#metal').Extender('add50'); and pass in your method as an option. jsFiddle Update

这篇关于无法在简单的jquery插件中调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆