我有一个缩略图滚动器,我想仅当鼠标在缩略图上悬停 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/