Javascript 迭代器不起作用,但硬编码数字可以

标签 javascript loops google-maps-api-3

我正在尝试使用谷歌地图 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/

相关文章:

javascript - jQuery 鼠标悬停淡入淡出效果

performance - 多次迭代或复杂的代码?

python - 比较日期的 strptime 替代方法?

google-maps - 如何使用 Google 路线服务获取具有不同交通方式的多个航点的路线?

javascript - 所选城市地点自动填充的偏差结果

javascript - 在 for 循环中设置 Javascript 变量

javascript - WebGL : Set opacity when using texture2D()

javascript - 即使使用 document.getElementById ('xyz' ).playVideo() 也无法控制 Youtube 嵌入 - 不是函数?

java - 在两个循环之外访问字符串数组

javascript - Google Maps/jQuery - 从 json 文件创建对象