我这里有一些代码:http://bitbucket.org/natim/lo53_tp1/src/tip/part3/camions/medias/js/tracking.js
我用它来绘制一些有关卡车方向的信息。
问题来自于 for 循环中定义的函数,如下所示:
...
for(i = 0; i < nb_trucks; i++)
{
...
contentString = '<div id="content">'+ trucks[i]['name'] + '</div>';
current_window = new google.maps.InfoWindow({
content: contentString
});
infosWindow.push(current_window);
current_marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(trucks[i]['end']['lat'], trucks[i]['end']['lon']),
draggable: false,
title: trucks[i]['name']
});
markers.push(current_marker);
google.maps.event.addListener(current_marker, 'click', function() {
current_window.open(map, current_marker);
});
}
在此代码中,您可以看到最后一个 block
google.maps.event.addListener(current_marker, 'click', function() {
current_window.open(map, current_marker);
});
我的问题是addListener参数中的current_marker与函数内部的不同。
函数内的 current_window 和 current_marker 在每次循环时都会被覆盖。
我怎样才能做到正确?
谢谢
最佳答案
将其包裹在 closure 中(只是这一小部分,没有其他更改)这样你就可以得到你想要的变量,如下所示:
(function(marker) { //a copy is passed, accessible as marker inside this function
google.maps.event.addListener(marker, 'click', function() {
current_window.open(map, marker);
});
})(current_marker); //pass in the current value
这并不引用改变每个循环的同一个变量,它的副本被传递到闭包中,因此每次运行它时,它都会获得 current_marker
的副本那段时间已经过去了。如果您对此更好奇,there are some great answers explaining closures in this question .
关于javascript - Javascript中的内联函数和全局变量问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2943713/