如何将按钮添加到 LeafletJS 标记内的 运行 代码?

How to add a button to run code inside LeafletJS marker?

我正在尝试在指针内添加一个按钮,用于将日志打印到控制台。这只是一个测试,所以我实际上可以使标记 运行 成为一种方法,但我什至无法让它打印文本。

const marker = L.marker([latitude, longitude]).addTo(map);

const button = '<br/><button type="button">Click button</button>'
const clickbutton = document.querySelector("#click");
button1.addEventListener("click", function(event) {
    console.log('This button works!');
});
marker.bindPopup(button);

当我加载页面时,我立即收到此错误:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'addEventListener')

控制台说这个错误是由

引起的
button1.addEventListener("click", function(event) {

但我不确定为什么它为空。谁能帮帮我?

您创建的按钮不正确。

这样就对了:

const button = document.createElement('button');

button.id = 'delete';
button.textContent = 'Delete marker';

为了向页面添加按钮,您需要找到所需的父元素并将按钮添加为子元素:

// replace this id with what you need
const buttonParrentId = 'button-parrent-id';

const buttonParrent = document.getElementById(buttonParrentId);
buttonParrent.appendChild(button);

接下来,您可以根据需要使用按钮:

const marker = L.marker([latitude, longitude]).addTo(map);

button.addEventListener("click", function(event) {
    console.log('This button works!');
});

marker.bindPopup(button);

结果代码示例:

const button = document.createElement('button');

button.id = 'delete';
button.textContent = 'Delete marker';

// replace this id with what you need
const buttonParrentId = 'button-parrent-id';

const buttonParrent = document.getElementById(buttonParrentId);
buttonParrent.appendChild(button);

const marker = L.marker([latitude, longitude]).addTo(map);

button.addEventListener("click", function(event) {
    console.log('This button works!');
});

marker.bindPopup(button);

More about createElement