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

标签 jquery plugins

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

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 Update

关于jquery - 无法在简单的 jquery 插件中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078481/

相关文章:

javascript - 日期选择器选项不起作用

javascript - 将模板添加到 div 内的 img 前面

jquery - 添加页面会在我的第一页下方创建一个空白

jQuery 中止请求

Eclipse maven 插件在检索 jar 时获取 HTTP 416

jquery - 100% 高度,无滚动条

用于 firefox 扩展的 python?

node.js - Node.js插件权限

java - 在 UI 线程上运行 Eclipse Plugin Activator 的 .start() 方法

java - 在不安装 java 的情况下为 Internet Explorer 启用 java 插件