問(wèn)題描述
我正在嘗試在某些事件(例如,按鈕單擊)上打開(kāi)特定標(biāo)記的彈出窗口.為此,我將 id 屬性添加到標(biāo)記并將所有標(biāo)記存儲(chǔ)在數(shù)組中.但是由于某種原因,當(dāng)我嘗試訪(fǎng)問(wèn)數(shù)組內(nèi)的標(biāo)記的 id 屬性時(shí),它是未定義的.
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);
}
更新好的,我找到了解決方案:我應(yīng)該將 for
替換為
UPDATE
Ok, I found the solution: I should replace for
with
for(var i = 0; i < markers.length; ++i)
并以 markers[i]["id"]
但是誰(shuí)能解釋一下為什么第一個(gè)版本不起作用?
But can someone explain me why the first version doesn't work?
推薦答案
我認(rèn)為你的錯(cuò)誤是使用push(在markers.push(marker)中)
I think your mistake is the use of push (in markers.push(marker))
要存儲(chǔ)標(biāo)記,您應(yīng)該使用
To store the markers, you should use
markers["id"] = marker;
你可以這樣打開(kāi)你的彈出窗口
You can open your popup like that
markers["id"].openPopup();
讓標(biāo)記知道他們的 id
For the markers to know their id
marker.id = "id";
這篇關(guān)于傳單在按鈕單擊時(shí)打開(kāi)特定標(biāo)記彈出窗口的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!