开发者

Javascript iterator won't work but hardcoded number will

开发者 https://www.devze.com 2023-03-01 08:17 出处:网络
I\'m trying to create dynamic markers using google maps api and am having problems when using a variable tat is iterated over.

I'm trying to create dynamic markers using google maps api and am having problems when using a variable tat is iterated over.

I've ommited the code for generating the markers and the map because it seems to work fine. This is the code for generating the info window.

This code produces the error of 'this_marker_info[$n]' [undefined] is not an object

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]);
   });      
}

This code works

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]);
   });      
}

All I did was swap $n with the number 0 in the second example in the lin开发者_如何转开发e tat reads "this_marker_info[$n].open(map, this_marker[$n]);"

Any help would be appreciated


This is a typical closure problem. By the time this_marker_info[$n].open(map, this_marker[$n]); gets executed you've finished the loop and the value of $n is business.length.

The solution is to write a closure:

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
}


Using Array.forEach() is a nice tidy way to fix it:

business.forEach(function(item, $n) {
   google.maps.event.addListener(this_marker[$n], 'click', function() {
       this_marker_info[$n].open(map, this_marker[$n]);
   });      
}

This way, the containing function never increments $n, so it will reliably keep it's original value.

To use Array.forEach() in older browsers, see this.

0

精彩评论

暂无评论...
验证码 换一张
取 消