开发者

Jquery plugin using methods needs to call itself

I'm following the tutorial here: 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 = funct开发者_如何学JAVAion(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');

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜