jquery将其传递给变量函数

jquery passing this to variable function

本文关键字:变量 函数 jquery      更新时间:2023-09-26

我正在尝试制作自己的图像旋转器,如果屏幕上有多个图像旋转器,它将起作用。这是我到目前为止得到的:

// 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);

问题是:rotatorImageChangeFunc = function(item) {项没有传递给函数。所以在该函数中,我正在为项目定义。为什么会这样,我该怎么说?

传递给 proxy 的上下文参数将作为 this 传递给函数,而不是作为参数。只需将item更改为this即可。


旁注:在你的主函数中,你有几个$(this).find(...)。插件函数看到的this已经是一个 jQuert 对象(这就是下面的this.each(...)工作的原因(,无需再次调用$()。只是this.find(...).

$.proxy只为包装的函数设置this - 它不对函数参数执行任何操作。

setInterval() 将调用没有参数的代理函数,因此原始函数也是如此 - item 将是未定义的。

若要修复,请从函数的声明中删除item,然后执行以下操作:

var item = this;

在函数的第一行。

[或用 this 重命名对item的所有引用]。

您尚未定义变量项 anaywhere。