setTimeout函数中未定义的JavaScript变量 [英] JavaScript variables undefined within setTimeout function
问题描述
我有以下代码:
for (var i = 0; i < markers.length; i++) {
var lat = markers[i][0];
var lng = markers[i][1];
var img = markers[i][2];
var info = markers[i][3];
setTimeout(function(lat, lng, img, info) {
console.log(lat + ', ' + lng);
$('#map').gmap3({
action: 'addMarker',
latLng:[lat, lng],
options:{
animation: google.maps.Animation.DROP,
icon: img
},
events:{
click: function(marker, event, data){
$(this).gmap3({action:'addinfowindow', anchor:marker, options:{content: '<div id="content" style="width:300px;height:250px;"><img src="' + info + '"></img></div>'}});
/*var infowindow = $(this).gmap3({action:'get', name:'infowindow'});
infowindow.close();*/
},
}
});
}, i* 100);
}
console.log显示lat和lng的未定义.为什么会这样?
The console.log is showing undefined for lat and lng. Why is this?
以前,我没有在超时内将任何变量传递给该函数,而是对它们进行了定义,但是它为for循环中的每个标记使用了相同的变量,这显然是错误的!
Previously I didn't pass any variables into the function within timeout and they WERE defined but it used the same one for each marker in the for loop which was obviously wrong!
有什么想法吗?
推荐答案
lat
和lng
是超时函数的命名参数,但是setTimeout
不会将任何参数传递给该函数,因此它们保持未定义状态.
lat
and lng
are named parameters of your timeout function, but setTimeout
does not pass any parameters to that function, so they remain undefined.
您应该将超时设置移到一个单独的函数中,以便为您的变量建立闭包:
You should move the timeout setup into a separate function, in order to establish a closure for your variables:
function configureTimeout(i, lat, lng, img, info) {
setTimeout(function() {
console.log(lat + ', ' + lng);
$('#map').gmap3({
action: 'addMarker',
latLng:[lat, lng],
options:{
animation: google.maps.Animation.DROP,
icon: img
},
events:{
click: function(marker, event, data){
$(this).gmap3({action:'addinfowindow', anchor:marker, options:{content: '<div id="content" style="width:300px;height:250px;"><img src="' + info + '"></img></div>'}});
/*var infowindow = $(this).gmap3({action:'get', name:'infowindow'});
infowindow.close();*/
},
}
});
}, i* 100);
}
for (var i = 0; i < markers.length; i++) {
var lat = markers[i][0];
var lng = markers[i][1];
var img = markers[i][2];
var info = markers[i][3];
configureTimeout(i, lat, lng, img, info);
}
这篇关于setTimeout函数中未定义的JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!