如何在弹出窗口中添加按钮并在函数中添加onClick
?
.setPopup(new mapboxgl.Popup({ offset: 25 })
.setHTML('<button onclick=' + { this.handlePop } + '> Button</button>'))
.addTo(map);
它不起作用。
答案 0 :(得分:1)
您可以使用此按钮将EventListner添加到按钮。
const btn = document.getElementsByClassName("btn")[0];
btn.addEventListener("click", () => {
console.log("hello");
});
我在这里添加了React的工作示例。您可以找到它here
var popup = new mapboxgl.Popup()
.setLngLat([-96, 37.8])
.setHTML(
`<h1>Hello World!</h1>
<button class="btn" ref=${this.buttonRef.current}>todo</button>`
)
.addTo(map);
const btn = document.getElementsByClassName("btn")[0];
btn.addEventListener("click", () => {
console.log("hello");
});
答案 1 :(得分:1)
以下功能将为给定坐标添加一个弹出按钮。希望对您有所帮助!
map.on('click',function() {
var coordinates = [-77.03171253204346, 38.91457788952212];
var description = "<button onclick=' + { this.handlePop } + '> Button</button>"
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
还请参阅Mapbox documentation,它非常方便和干净!
mapboxgl.accessToken = 'place your mapbox token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-77.04, 38.907],
zoom: 11.15
});
map.on('load', function() {
map.on('click',function() {
var coordinates = [-77.03171253204346, 38.91457788952212];
var description = "<button onclick=' + { this.handlePop } + '> Button</button>"
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(description)
.addTo(map);
});
// Change the cursor to a pointer when the mouse is over the places layer.
map.on('mouseenter', 'places', function() {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'places', function() {
map.getCanvas().style.cursor = '';
});
});
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.mapboxgl-popup {
max-width: 400px;
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
}
<div id="map"></div>
答案 2 :(得分:1)
我解决问题的方法是使用 setDOMContent 而不是 setHTML 。
这样,您可以像这样轻松地操纵每个元素发生的事情
const name = 'abc';
const innerHtmlContent = `<div style="min-width: 600px;font-size: large;color : black;">
<h4 class="h4Class">${name} </h4> </div>`;
const divElement = document.createElement('div');
const assignBtn = document.createElement('div');
assignBtn.innerHTML = `<button class="btn btn-success btn-simple text-white" > Assign</button>`;
divElement.innerHTML = innerHtmlContent;
divElement.appendChild(assignBtn);
// btn.className = 'btn';
assignBtn.addEventListener('click', (e) => {
console.log('Button clicked' + name);
});
const popup = new mapboxgl.Popup({
offset: 25
})
.setDOMContent(divElement);