监听器和Google地图标记的关闭问题 [英] Closure issue with Listener and Google Maps markers

查看:137
本文介绍了监听器和Google地图标记的关闭问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为每个生成的标记添加一个Listener事件,这样当您单击标记时,您将被重定向到permalink url。使用下面的代码永久链接值是相同的每个标记(它得到的最后一个值)。我已阅读关闭问题,这似乎是我所拥有的。虽然我并没有看到我看过的例子。

I want to add a Listener event to each generated marker, so that when you click a marker you are redirected to the permalink url. With the code below the permalink value is the same for every marker(it get's the last value). I've read about closure problems and that seems to be what I'm having. I don't really get the examples I've looked at though.

有人可以看看我的代码并指出我的方向正确吗?

Can somebody take a look at my code and point me in the right direction? Any help is greatly appreciated!

downloadUrl("http://localhost/map/generatexml.php", function(data) {
            var xml = parseXml(data);
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
              var permalink = markers[i].getAttribute("permalink");
              var point = new google.maps.LatLng(
                  parseFloat(markers[i].getAttribute("lat")),
                  parseFloat(markers[i].getAttribute("lng")));
              var marker = new google.maps.Marker({map: map,position: point,icon: icon.icon,shadow: icon.shadow,title: name});
              google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;});
            }


推荐答案

试试这个:

for (var i = 0; i < markers.length; ++i) {
  // ... like what you have already ...
  (function(permalink) {
    google.maps.event.addListener(marker, 'click', function() {self.location.href = permalink;});
  })(permalink);
}

通过创建一个带有permalink值的副本的新词法作用域每次迭代,您的处理程序应该更好地工作。

By making a new lexical scope with a copy of the "permalink" value at each iteration, your handlers should work better.

这篇关于监听器和Google地图标记的关闭问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆