简体   繁体   English

如何在事件侦听器中使用局部变量?

[英]How can I use a local variable in an event listener?

My problem is with using the Google Maps API, but I'm pretty certain it is a general JavaScript problem.我的问题是使用 Google Maps API,但我很确定这是一个普遍的 JavaScript 问题。

I have a local array of objects defining a series of markers.我有一个定义一系列标记的本地对象数组。 Processing these objects is no problem.处理这些对象是没有问题的。 But I want to use one of the values in an event handler I create, and the value is always "undefined" by the time that event handler is called.但是我想在我创建的事件处理程序中使用其中一个值,并且在调用该事件处理程序时该值始终是“未定义的”。 (Which is logical, since the value was part of a local array, but I don't know how I can solve this.) (这是合乎逻辑的,因为该值是本地数组的一部分,但我不知道如何解决这个问题。)

The code:编码:

var markers = [
   { lat: 58, lng: 07, title: 'Marker 01', url: 'article.aspx' },
   .... /* etc */
]
for (var idx in markers) {
  var marker = new google.maps.Marker({ 
    position: new google.maps.LatLng( markers[idx].lat, markers[idx].lng ), 
    title: markers[idx].title,
    map: map
  });
  google.maps.event.addListener( marker, 'click', function() {
    window.location.href = markers[idx].url;
  });
}

When I click on one of the markers in the final map (ie. trigger the 'click' listener), I am redirected to a page called 'undefined', because the 'url' attribute no longer has a value.当我点击最终地图中的一个标记(即触发“点击”侦听器)时,我被重定向到一个名为“未定义”的页面,因为“url”属性不再具有值。 How do I fix this?我该如何解决?

也许您可以将 url 传递给调用 addListener 的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM