setInterval一直给我未定义的函数

setInterval keeps giving me undefined function

本文关键字:函数 未定义 一直 setInterval      更新时间:2023-09-26

在我的代码中有这个函数,它作为类中的元素的滑动条。
我想要setInterval到它的点击事件,但一直给我的功能是未定义的。

下面是我的脚本:
$(document).ready(function(){
    $(".slide").click(
        setInterval( function fadeNext() {
            $(this).children('div:nth(0)').children('img:nth(0)').fadeOut().appendTo($(this).children("div:nth(1)"));
            $(this).children("div:nth(1)").children('img:nth(0)').fadeIn().appendTo($(this).children("div:nth(0)"));
        },1000)
    );
});

在setInterval函数中,this属于匿名函数,不属于点击函数。所以你需要在间隔时间内通过this。解决方案是在匿名函数

上使用bind
$(document).ready(function () {
$(".slide").click(function(){
    setInterval(function fadeNext() {
        $(this).children('div:nth(0)').children('img:nth(0)').fadeOut().appendTo($(this).children("div:nth(1)"));
        $(this).children("div:nth(1)").children('img:nth(0)').fadeIn().appendTo($(this).children("div:nth(0)"));
    }.bind(this), 1000)
)
});
});

或者只是

$(document).ready(function () {
$(".slide").click(function(){
var _this = this;
    setInterval(function fadeNext() {
        $(_this).children('div:nth(0)').children('img:nth(0)').fadeOut().appendTo($(this).children("div:nth(1)"));
        $(_this).children("div:nth(1)").children('img:nth(0)').fadeIn().appendTo($(this).children("div:nth(0)"));
    }, 1000)
)
});
});

可以尝试使用jQuery延迟和fadeOut回调。我自己没有测试过。

$(document).ready(function(){
    $(".slide").click(function () {
            $(this)
                .children('div:nth(0)')
                    .children('img:nth(0)')
                    .delay(1000);
                    .fadeOut(400, function(){
                        $(this).appendTo($(this).children("div:nth(1)"));
                    });
    });
});