我正在尝试使用谷歌地图 API 创建动态标记,但在使用迭代变量 tat 时遇到问题。
我省略了生成标记和 map 的代码,因为它看起来工作正常。这是生成信息窗口的代码。
此代码产生“this_marker_info[$n]”[undefined] 不是对象的错误
for(var $n = 0; $n < business.length; $n++){
google.maps.event.addListener(this_marker[$n], 'click', function() {
this_marker_info[$n].open(map, this_marker[$n]);
});
}
此代码有效
for(var $n = 0; $n < business.length; $n++){
google.maps.event.addListener(this_marker[$n], 'click', function() {
this_marker_info[0].open(map, this_marker[0]);
});
}
我所做的就是在第二个示例中将 $n 与数字 0 交换,该行的内容为“this_marker_info[$n].open(map, this_marker[$n]);”
如有任何帮助,我们将不胜感激
最佳答案
这是一个典型的闭包问题。
当 this_marker_info[$n].open(map, this_marker[$n]);
执行时,您已经完成了循环,并且 $n
的值为 business.length
.
解决方案是编写一个闭包:
for(var $n = 0; $n < business.length; $n++){
(function ($the_actual_n) {
google.maps.event.addListener(this_marker[$the_actual_n], 'click', function() {
this_marker_info[$the_actual_n].open(map, this_marker[$the_actual_n]);
});
}($n)); // <-- call this 'anonymous' function with $n
}
关于Javascript 迭代器不起作用,但硬编码数字可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5811613/