Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将变量传递到setTimeout?_Javascript_Jquery - Fatal编程技术网

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的源代码