开发者

jQuery custom functions and passing parameters to them

I have a row of images, and when one of the images is clicked it expands while also shrinking any other image that may be enlarged. If you click on the enlarged image, it just shrinks itself.

I'm receiving a 'shrink is not defined' error message. Thanks in advance.

        $.fn.grow = function(size,rate) {
            $(this).addClass('click')开发者_运维知识库.animate({'height': size}, rate);
        }
        $.fn.shrink = function(size,rate) {
            $('img').removeClass('click').animate({'height': size}, rate);
        }

        $(document).ready(function() {
            $('#gallery img').click(function() {
                var $this = $(this);
                ($this.hasClass('click')) ? $this.shrink('139', '200') : $this.shrink('139', '200').grow('700', '200');
            });
        });


I received a different exception...

Uncaught TypeError: Cannot call method 'grow' of undefined

You are attempting to chain the methods (or use the cascade if you like Crockfordian terms), but neither of your custom functions returns a jQuery object.

You need to make them return something, generally this. In a jQuery custom function, this is already a jQuery object, so there is no need to wrap it again.


If you use $.fn.extend like that:

$.fn.extend({
    shrink: function() {$(this).doSth()},
    grow: function() {$(this).doSth()}
});

You will be able to apply your shrink and grow methods to any jQuery wrapped object eg

$('img').shrink();

Hope it helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜