javascript - setInterval 不断给我未定义的函数

标签 javascript jquery

我的代码中有这个函数,它可以用作类中元素的 slider 。
我要 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属于匿名函数,而不是click函数。所以你需要在区间内传递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)
)
});
});

关于javascript - setInterval 不断给我未定义的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24365529/

相关文章:

javascript - Internet Explorer 中的多行 js 正则表达式替换

javascript - Javascript 中的波浪排序

javascript - Ruby on Rails - 在 View 文件夹目录中添加额外的 JavaScript 文件是否正确?

javascript - 如何将数据从 .txt 文件加载到文本区域

javascript - 使用 Puppeteer 获取所有纯文本

javascript - Angular JS Slick Carousel - 似乎不起作用

javascript - 如何在立即使用 jQuery 或 JavaScript 粘贴时删除所有空格?

jquery - 元素不可点击, ruby

javascript - 变量不打印到屏幕 - angularjs

javascript - 正在向 url 添加搜索条件,但无法返回