問題描述
我正在嘗試在某些事件(例如,按鈕單擊)上打開特定標記的彈出窗口.為此,我將 id 屬性添加到標記并將所有標記存儲在數組中.但是由于某種原因,當我嘗試訪問數組內的標記的 id 屬性時,它是未定義的.
I'm trying to open a specific marker's popup on some event(say, button click). In order to do so I add an id property to a marker and store all markers in an array. But for some reason, the id property of a marker inside of an array is undefined when I try to access it.
var map = L.map('map').setView([51.505, -0.09], 13);
var markers = [];
var marker = L.marker([51.5, -0.09]);
marker["id"]="0";
marker.bindPopup('!');
marker.addTo(map);
markers.push(marker);
openPopupById("0");
function openPopupById(id) {
for(var marker in markers) {
alert("Marker's id " + marker["id"] + " target id " + id );
if (marker["id"] === id) {
//marker.openPopup();
alert("opening " + id);
}
}
alert(id);
}
更新好的,我找到了解決方案:我應該將 for
替換為
UPDATE
Ok, I found the solution: I should replace for
with
for(var i = 0; i < markers.length; ++i)
并以 markers[i]["id"]
但是誰能解釋一下為什么第一個版本不起作用?
But can someone explain me why the first version doesn't work?
推薦答案
我認為你的錯誤是使用push(在markers.push(marker)中)
I think your mistake is the use of push (in markers.push(marker))
要存儲標記,您應該使用
To store the markers, you should use
markers["id"] = marker;
你可以這樣打開你的彈出窗口
You can open your popup like that
markers["id"].openPopup();
讓標記知道他們的 id
For the markers to know their id
marker.id = "id";
這篇關于傳單在按鈕單擊時打開特定標記彈出窗口的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!