我尝试为侧边栏项目列表设置一些eventListeners。 边栏中最多有12个项目。所有按钮标识符类都在那里。
例如,如果我这样做,它将起作用:
function flyToLocation(selector, lng, lat) {
let el = document.querySelector(selector);
el.addEventListener('click', () => {
// REMOVE ALL CLASS .active
removeActives();
// ADD CLASS .active
el.classList.add('active');
map.flyTo({
center: [
lng,
lat
],
zoom: 15,
})
});
}
并执行以下功能:
flyToLocation('.btn-alster',
lngLatLocation[0].coordinates[0],
lngLatLocation[0].coordinates[1]);
但是我想做的是在forEach中设置函数,所以我不需要设置所有硬编码的eventListeners,例如:
lngLatLocation.forEach((item) => {
console.log(item.coordinates);
console.log(item.id);
flyToLocation(item.id, item.coordinates[0], item
.coordinates[1]);
});
这没有用,我也不知道为什么。控制台告诉我:
TypeError: Cannot read property 'addEventListener' of null
at flyToLocation (mapbox.js:4)
at mapbox.js:145
at Array.forEach (<anonymous>)
at mapbox.js:141