Javascript:将参数传递给内部 setTimeOut 函数?

标签 javascript arguments settimeout

我有一个缩略图滚动器,我想仅当鼠标在缩略图上悬停 3 秒时才触发某些操作。我有以下代码,但内部 setTimeOut 函数未从外部函数获取参数 - sourceURL 控制台输出出现“undefined”错误。但是“hover”函数我确实看到了正确的sourceURL值。 提前致谢!

   var tOut;
   $('img.thumb').hover(function(){
      var sourceURL = $(this).attr('src');
      var lat = $(this).attr('lat');
      var lng = $(this).attr('lng');
      tOut = setTimeout(function(sourceURL,lat,lng){
      console.log(sourceURL);//undefined
      map.setView(new L.LatLng(lat, lng), (init_mapzoom+2));
    },3000);
   },function(){
     clearTimeout(tOut);
  });

最佳答案

您不需要将变量传递给函数。由于函数是在变量存在的作用域中创建的,因此它们被捕获在函数的闭包中,因此即使作用域消失后,函数也可以使用它们:

var tOut;
$('img.thumb').hover(function(){
  var sourceURL = $(this).attr('src');
  var lat = $(this).attr('lat');
  var lng = $(this).attr('lng');
  tOut = setTimeout(function(){
    console.log(sourceURL);
    map.setView(new L.LatLng(lat, lng), (init_mapzoom+2));
  },3000);
},function(){
  clearTimeout(tOut);
});

关于Javascript:将参数传递给内部 setTimeOut 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26933117/

相关文章:

javascript - Paypal智能按钮结账无需发货

javascript函数反转文本颜色

Javascript:如何在 onClick 完成之前更新页面?

javascript - 使用 props 代替 state

javascript - jquery 使用 Promise 和反向地理编码获取用户位置

command-line - 如何将命令行参数传递给 PowerShell ps1 文件

以泛型类作为参数的 Java 方法

python - Python 如何以不同方式接收标准输入和参数?

javascript - 设置超时,绑定(bind)和这个

javascript - setTimeout 中的 Jquery 单击处理程序