【发布时间】:2019-05-24 07:06:03
【问题描述】:
这是一个 javascript 初学者问题。
我在固定位置(传单)创建了一个自定义弹出窗口。单击打开弹出窗口的标记后,我无法通过单击关闭按钮来关闭它。虽然我可以单击不同的标记,但弹出包装仍然打开,显示附加到每个不同标记的内容。因此,通过单击标记会更改弹出窗口的内容,但无法通过单击关闭按钮关闭弹出窗口。
我尝试了一个事件监听器。
我需要完成这项工作的那段代码。
任何帮助将不胜感激。
// Adds custom marker
var redFlag = L.icon({
iconUrl: 'images/mapmarker2.png',
iconSize: [34, 34],
iconAnchor: [17,34]
});
// Adds markers and popup
// geoJSON file stored in 'art' variable
const myLayer = L.geoJSON(art, {
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {icon: redFlag});
},
onEachFeature: function ( feature, layer) {
layer.on('click', function(e){
// popup content
var getWrap = document.getElementById('wrapper');
var wrap = getWrap.appendChild(document.createElement('div'));
wrap.className = 'wrapper';
wrap.innerHTML =
`<div class="close">X</div>`+
`<div class="popUpContent" style="background-color:#e8f4ff">`+
`<div class='pic'><img src =
"images/${feature.properties.image}"></div>`+
`<div class="puName"><span
class="puName">${feature.properties.name}</span><br>`+
`<span class="puTitle">"${feature.properties.title}"</span><br>`+
`<div class="extra3">${feature.properties.extra}</div></div>`+
`</div>`;
if(!feature.properties.title){
wrap.innerHTML =
`<div class="close">X</div>`+
`<div class="popUpContent" style="background-color:#e8f4ff">` +
`<div class='pic'><img src =
"images/${feature.properties.image}"></div>`+
`<div class="puName"><span
class="puName">${feature.properties.name}</span><br>`+
`<div class="extra3">${feature.properties.extra}</div></div>`+
`</div>`;
}
// Add eventlistener to the close button
document.querySelector('.close').addEventListener( 'click', closePopup);
function closePopup(e){
if(event.target.matches('.close')){
document.querySelector(".wrapper").style.display='none'
}else if(document.querySelector(".wrapper").style.display='block'){
document.querySelector(".wrapper").style.display='none';
}
}
});
}
});
mymap.addLayer(myLayer)
【问题讨论】:
-
对于
document.getElementById("wrapper").style.display === 'block',您不需要3x=并且您的else条件正在为wrapper执行相同的样式,因此该if条件的结果是没有意义的。您还复制了我不推荐的wrapperid。 -
感谢 NewToJS,我更改了那段代码,但仍然遇到同样的问题。
-
您仍在创建
wrapper的重复 ID。 ID 应该是唯一的。在document.getElementById("wrapper").innerHTML中,您还添加了具有相同id的div=><div id="wrapper" style="background-color:white;">
标签: javascript popup leaflet