我有以下代码:
$('.p1').click(function(){
var num = 10;
var count = 0;
var intv = setInterval(anim,800);
function anim(){
count++;
num--;
if(num==0){clearInterval(intv);}
$(this).hide(function(){
$(this).appendTo('#box_'+count);
}).delay(500).fadeIn();
}
anim();
});
我不知道,如果动画放入函数时出现错误,请帮助我
最佳答案
anim()
函数没有 this
上下文。点击事件确实有它,但它不会自动传递给您的其他函数。您可以使用 .bind()
和 .call()
进行设置:
var intv = setInterval(anim.bind(this),800);
...
...
anim.call(this);
.bind()
用在 setInterval
行上,因为您希望在设置 this
上下文的同时传递函数(不调用它)。 .call()
用在最后一行,因为您想要调用该函数并设置 this
上下文。
或者,您可以将 this
上下文存储为另一个变量,以便在 anim()
函数中访问它:
// in the click event
var element = this;
function anim(){
count++;
num--;
if(num==0){clearInterval(intv);}
$(element).hide(function(){
$(element).appendTo('#box_'+count);
}).delay(500).fadeIn();
}
关于javascript - 未捕获的类型错误 : Cannot use 'in' operator to search for 'height' in undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28294032/