简体   繁体   English

jQuery插件使用方法需要自行调用

[英]Jquery plugin using methods needs to call itself

I'm following the tutorial here: http://docs.jquery.com/Plugins/Authoring 我在这里关注该教程: http : //docs.jquery.com/Plugins/Authoring

I just wanted to create a simple plugin for a project we are working on that would add +/- signs next to an input box that could be used to increment the value of the box. 我只是想为我们正在研究的项目创建一个简单的插件,该插件会在输入框旁边添加+/-符号,该符号可用于增加该框的值。

So I'm reading the tutorial and doing the section that talks about having multiple methods and everything is going fine, except for one small hitch. 因此,我正在阅读教程,并做有关讨论具有多种方法的部分的工作,除了一个小问题,一切都很好。

So here is the code: 所以这是代码:

(function( $ ) {
    var methods = {
        init: function(options) {
            if (options) {
                $.extend(settings, options);
            }

            this.css('float', 'left');
            this.after('<div class="increment-buttonset"><div class="increment-button" style="float: left;">+</div><div class="decrement-button">-</div></div><br style="clear: both" />');
            $('.increment-button').click(function() {
                $.increment('change');
            });
            return this;
        },
        change: function() {
            // Increment Decrement code would go here obviously
            return this;
        }
    };

    $.fn.increment = function(method) {
        var settings = {
            'step': 1
        };

        if (methods[method]) {
            return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        }
    };
})( jQuery );

The issue is the $.increment('change'); 问题是$ .increment('change');

I want to bind the +/- buttons on click to call the increment('change'). 我想绑定单击上的+/-按钮以调用增量(“更改”)。 I get errors when I do that. 我这样做时会出错。

Uncaught TypeError: Object function (a,b){return new c.fn.init(a,b)} has no method 'increment'

I've tried it without the $. 我试过没有$。 but that just tells me increment isn't defined yet. 但这只是告诉我增量尚未定义。 Am I messing some syntax up here or just going about this completely wrong? 我在这里弄乱一些语法还是只是完全解决了这个错误?

The solution is pretty simple, you were calling the method the wrong way. 解决方案非常简单,您以错误的方式调用了该方法。 It should be 它应该是

$('.increment-button').click(function() {
    $(this).increment('change');
});

That is, because function added to $.fn.functionName can only be called on a jQuery elements like $(selector).functionName. 也就是说,由于添加到$ .fn.functionName的函数只能在$(selector).functionName之类的jQuery元素上调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM