2014-11-14 55 views
0

我有一个缩略图滚动条,我只想在缩略图上将鼠标悬停3秒时触发某些动作。我有以下代码,但内部setTimeOut函数没有从外部函数获取参数 - sourceURL控制台输出得到'undefined'错误。但'hover'函数我确实看到了正确的sourceURL值。 在此先感谢!Javascript:将参数传递给内部setTimeOut函数?

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); 
    }); 
+0

谢谢。但是什么代码? – IrfanClemson 2014-11-14 15:19:34

+0

否。setTimeOut需要从悬停函数中获取参数。 – IrfanClemson 2014-11-14 15:20:17

回答

1

您不需要将变量传递给该函数。随着功能的范围内创建,其中存在变数,他们被发现在封闭的功能,所以该函数可以使用它们的范围变本加厉之后:

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); 
}); 
+0

谢谢!完美的工作。 – IrfanClemson 2014-11-14 15:31:07

1

functionsetTimeout不必须接受他们作为论据。

也被定义在.hover()function之内,它将在范围内具有sourceURL等。

$('img.thumb').hover(function(){ 
    var sourceURL = $(this).attr('src'); 
    // .. 

    tOut = setTimeout(function(){ 
    console.log(sourceURL); 
    // ... 
    }, 3000); 
}, ...); 

再次将它们作为命名参数将shadowvar S,所以只有参数是function中访问。

+0

谢谢!会接受你的答案,但Guffa的第一。 – IrfanClemson 2014-11-14 15:31:33