我的代码中有这个函数,它可以用作类中元素的 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/