[英]Javascript counter not being passed into google maps function
I'm sure this has to do with scope, but I always seem to struggle with javascript scope. 我敢肯定这与范围有关,但是我似乎总是在用JavaScript范围挣扎。
Anyway here is the code ... 无论如何,这里是代码...
var beaches = [
['Surf Spot One', xxxxxx, xxxxxx, 2],
['Surf Spot Two', xxxxxx, xxxxxx, 1],
['Surf Spot Three', xxxxxx, xxxxxx, 3 ]
];
var marker = [];
for (var i = 0; i < beaches.length; i++) {
var pos = new google.maps.LatLng(beaches[i][1], beaches[i][2]);
marker[i] = new google.maps.Marker({
setClickable: 1,
position: pos,
map: map,
icon: surferDude,
title:beaches[i][0]
});
google.maps.event.addListener(marker[i], 'mouseover', function() {
// do something here on mouseover
console.log(i);
});
}
The output in the console on mouseover is always 3? 鼠标悬停时控制台中的输出始终为3? Why is this? 为什么是这样? I need it to be 1 or 2 or 3 depending on which icon I'm mouseing over. 我需要将其设置为1或2或3,具体取决于我将鼠标悬停在哪个图标上。
Yes, it is about scope. 是的,这与范围有关。 When the callback gets called, it will be using the last value of i
rather than the value of i
when you add the listener. 当回调被调用时,它将使用i
的最后一个值而不是添加侦听器时的i
值。 The anonymous function that you're building is a closure that captures the i
variable without evaluating it, i
won't be evaluated until the callback is called and by that time, i
will be 3. 你正在构建的匿名函数则是抓住了一个封闭i
变量没有评估它, i
将不会被计算,直到调用回调到那个时候, i
将是3。
The usual closure busting solution should work: 常规的封闭清除解决方案应该可以工作:
function create_listener(i) {
return function() {
console.log(i);
};
}
//...
google.maps.event.addListener(marker[i], 'mouseover', create_listener(i));
You could also use a self-executing function instead of a separate create_listener
but that might be too noisy. 您也可以使用自执行函数代替单独的create_listener
但这可能太吵了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.