0

I'm currently working on a website that features a Google map with my custom markers on it. Each marker has its own link, and I can easily link each marker to a URL as follows (this example has only one of my markers) -

 var image = 'parkour.png';
 var locations = [
    new google.maps.Marker({
      position: new google.maps.LatLng(43.670231, -79.386821),
      map: map,
      url: "http://bit.ly/RDYwKQ",
      icon: image
    })
  ]
  google.maps.event.addListener(locations[0], 'click', function() {
    window.location.href = locations[0].url;
  });

As you can see, I am simply creating an array, adding an element, and then linking the element. This works fine. However, when I loop through each element to add a listener to each one, not a single marker has a link (they all still appear, and still cause the mouse to change as though there is a link, but clicking does nothing). Here is the code for that -

  var image = 'parkour.png';
  var locations = [
    new google.maps.Marker({
      position: new google.maps.LatLng(43.670231, -79.386821),
      map: map,
      url: "http://bit.ly/RDYwKQ",
      icon: image
    })
  ]
  for(x in locations) {
    google.maps.event.addListener(x, 'click', function() {
        window.location.href = x.url;
    })
  }

Note that the only change is that the elements are looped through and called in this way.

I've tried everything, from changing it to a normal for-loop, to creating a marker first and then adding it to the array, and I can't seem to find any fix.

Any suggestions?

4

1 回答 1

1

您不应该使用该for in语句来循环数组。该for in语句遍历对象的所有键并产生该键。要遍历数组,请改用简单的for循环。

此外,作为一种好的做法,您应该有一个var语句并尽可能限制属性查找。此外,你必须小心闭包:JavaScript 闭包内循环 - 简单的实际示例

var i = 0,
    len = locations.length,
    addListener = google.maps.event.addListener,
    l;

    for(; i < len; i++) {
        addListener((l = locations[i]), 'click', (function(l) {
            return function () {
                window.location.href = l.url;
            };

        })(l));
     }
于 2013-05-02T00:20:43.497 回答