Javascript 如何将变量传递到setTimeout?
以下是我的出席:Javascript 如何将变量传递到setTimeout?,javascript,jquery,Javascript,Jquery,以下是我的出席: $('md-card').each(function(index){ setTimeout(function(){ $(this).addClass('hietim'); },500*index); }); 目标是为md卡元素提供分层计时 它不起作用,因为$(this)在setTimeout(function(){})中没有任何含义。我还尝试: $('md-card').each(function(index){ var e =
$('md-card').each(function(index){
setTimeout(function(){
$(this).addClass('hietim');
},500*index);
});
目标是为md卡
元素提供分层计时
它不起作用,因为$(this)
在setTimeout(function(){})
中没有任何含义。我还尝试:
$('md-card').each(function(index){
var e = $(this)
setTimeout(function(e){
e.addClass('hietim');
},500*index);
});
$('md-card').each(function(index){
$(this).delay(500*index).addClass('hietim');
});
它将弹出一个jquery错误。还尝试:
$('md-card').each(function(index){
var e = $(this)
setTimeout(function(e){
e.addClass('hietim');
},500*index);
});
$('md-card').each(function(index){
$(this).delay(500*index).addClass('hietim');
});
它失败是因为
delay()
似乎不适用于addClass
只要不将变量传递到函数中,第二个选项就应该有效。然后,它将传递对e
的引用,创建一个闭包,该闭包将允许函数在setTimeout完成时使用该变量,而不管该范围是否继续存在
$('md-card').each(function(index){
var e = $(this)
setTimeout(function(){ // Remove the e here
e.addClass('hietim');
},500*index);
})) 即使你也可以尝试这种方法
$('md-card').each(function(index){
setTimeout(function(thisObj){
thisObj.addClass('hietim');
},500*index,$(this));
});
看看这里的函数细节说明。为此,我使用了元素的偏移量(从顶部和左侧) 您可以在上看到my的源代码