简体   繁体   中英

jquery passing this to variable function

I'm trying to make my own image rotator that will work if there is multiple image rotators on the screen. Here is what I have got so far:

// jQuery plugin to make image containers rotate.
(function($){

    // Swap text with title attribute
    $.fn.scWFWImageRotator = function() {

        var rotatorTimeSwap = 6000;

        $(this).find("img").removeClass("selected");
        $(this).find("img:first-child").addClass("selected");

        var rotatorImageChangeFunc = function(item) {
            var rotatorImages = $(item).children("img");
            var imgSelected = $(item).children("img.selected");
            var rotatorImgCount = rotatorImages.length;
            var rotatorCurImage = $(imgSelected).index(rotatorImages);
            alert(item);
        }

        return this.each(function() {

            var rotatorTimer;
            var $this  = $(this);
            var func = $.proxy( rotatorImageChangeFunc, $this );

            rotatorTimer = setInterval(func, rotatorTimeSwap);

            $this.hover(
                function() { rotatorTimer = clearInterval(rotatorTimer); },
                function() { rotatorTimer = setInterval(func, rotatorTimeSwap); }
            );

        });

    };

})(jQuery);

Problem is: rotatorImageChangeFunc = function(item) { item is not getting passed to the function. So inside that function I'm getting undefined for item. Why is this the case and how do I put it right?

The context parameter you pass to proxy is passed to the function as this , not as an argument. Just change item to this .


Side note: In your main function, you have a couple of $(this).find(...) s. The this that plug-in functions sees is already a jQuert object (which is why your this.each(...) below works), no need to call $() on it again. Just this.find(...) .

$.proxy only sets this for the wrapped function - it doesn't do anything with function parameters.

setInterval() will call your proxyed function with no parameters and therefore so will the original - item will be undefined.

To fix, remove item from the function's declaration, and do:

var item = this;

in the first line of the function.

[or rename all references to item with this ].

您尚未定义变量项目anaywhere。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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