我试图使用以下代码将点击标记的标题存储在全局变量中:
var selectedUser; //returns undefined
function attachSecretMessage(marker, secretMessage) {
var infowindow = new google.maps.InfoWindow({
content: secretMessage
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
selectedUser = secretMessage;
console.log(selectedUser); //Gives title of selected marker
});
}
function selectedUser () {
document.write(selectedUser); // returns undefined
}
以下是我在HTML中调用selectedUser()的方法:
<div class="selectedUsername">
<h2><script type="text/javascript">selectedUser();</script></h2>
</div>
但我只是返回未定义。我该如何解决这个问题,并能够存储点击标记的标题并在其他地方访问它?
答案 0 :(得分:2)
它确实在全局变量中写入它。而你的console.log证明了这一点。我认为你的selectedUser()函数在点击发生之前执行。这就是你未定义的原因..你的点击回调还没有被执行。尝试这样做(也改变名称):
var selectedUser; //returns undefined
function writeSelectedUser () {
docment.getElementByTagName('h2')[0].innerHTML = secretUser;
}
function attachSecretMessage(marker, secretMessage) {
var infowindow = new google.maps.InfoWindow({
content: secretMessage
});
marker.addListener('click', function() {
infowindow.open(marker.get('map'), marker);
selectedUser = secretMessage;
writeSelectedUser();
console.log(selectedUser); //Gives title of selected marker
});
}