我正在嘗試在傳單標記內添加一個按鈕,該按鈕將日志列印到控制臺。這只是一個測驗,所以我實際上可以讓標記運行一個方法,但我什至無法讓它列印文本。
const marker = L.marker([latitude, longitude]).addTo(map);
const button = '<br/><button type="button" id="delete">Delete marker</button>'
const deletebutton = document.querySelector("#delete");
button1.addEventListener("click", function(event) {
console.log('This button works!');
});
marker.bindPopup(button);
當我加載頁面時,我立即收到此錯誤:
未捕獲(承諾)型別錯誤:無法讀取 null 的屬性(讀取“addEventListener”)
控制臺說這個錯誤是由
button1.addEventListener("click", function(event) {
但我不確定為什么它為空。誰能幫我嗎?
uj5u.com熱心網友回復:
您正在錯誤地創建按鈕。
它會是這樣的:
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);
更多關于 createElement
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/337276.html
標籤:javascript 表达 按钮 传单 添加事件监听器
上一篇:類實體的出廠重置
下一篇:游標分頁mongodb貓鼬
