简体   繁体   English

我应该如何重组我的 addEventListener?

[英]How should I restructure my addEventListener?

I'm using Google Maps' API.我正在使用谷歌地图的 API。 I have an array of markers and an array of info windows, and I'm trying to get the respective info window to display when the marker is clicked.我有一组标记和一组信息窗口,我试图在单击标记时显示相应的信息窗口。 I'm having trouble understanding how I should add my event listener so that it respects JavaScript closures.我无法理解我应该如何添加我的事件侦听器以使其尊重 JavaScript 闭包。

(Incorrect) Code, all of which is contained in an initialize() that is called when the page loads: (不正确)代码,所有这些都包含在页面加载时调用的initialize()中:

var markers = []
var infoWindows = []

[define all markers and info windows here, long so cut]

for (var i = 0; i < markers.length; i++)
{
    google.maps.event.addListener(markers[i], 'click', function() {
        infoWindows[i].open(mymap, markers[i]);
    });
}

I've made sure that all of my objects are initialized properly before coming here.在来到这里之前,我已经确保我的所有对象都已正确初始化。

My understanding of my problem is that by the time the click event occurs, infoWindows[i] is no longer accessible.我对我的问题的理解是,当点击事件发生时, infoWindows[i]不再可访问。 What can I do about this so that the eventListener works as I think it should, where the infoWindow at the i-th position in the array corresponds to the marker at the i-th position?我该怎么做才能让eventListener像我认为的eventListener工作, infoWindow中第 i 个位置的infoWindow于第 i 个位置的标记?

You're right, infoWindows[i] is no longer accessible because the value of i has been updated.你说得对, infoWindows[i]不再可用,因为i的值已更新。

One way to solve this is to use .forEach :解决此问题的一种方法是使用.forEach

markers.forEach(function(value, i){
    google.maps.event.addListener(markers[i], 'click', function() {
        infoWindows[i].open(mymap, markers[i]);
    });
})

In this case the i variable for each event listener is in a different function.在这种情况下,每个事件侦听器的 i 变量位于不同的函数中。 Your current code uses the same i variable every time and the i variable in every event listener is the same.您当前的代码每次都使用相同的i变量,并且每个事件侦听器中的i变量都相同。 After all event listeners have been assigned i remains at its final value and markers[i] refers to the last marker in the list.在分配了所有事件侦听器后, i保持其最终值,而markers[i]指的是列表中的最后一个标记。

Check out this question for alternative solutions.查看此问题以获取替代解决方案。

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

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