我正在使用以下代码:
function eventListenerTest(event) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, function (data) {
address = data.rows[0];
alert("This gets executed afterwards");
});
alert("This gets executed first");
event.infoWindowHtml = "<b>Address: </b>" + address;
}
}
问题是在infoWindow中使用'address'变量后会执行$ .getJSON函数。修改了这样的代码:
function eventListenerTest(event) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, function (data) {
address = data.rows[0];
event.infoWindowHtml = "<b>Address: </b>" + address;
});
}
}
“event”对象似乎无法通过这种方式访问(Google Maps infoWindow中不显示任何内容)。我想我应该能够将'event'传递给JSON中的函数,但我不知道如何实现这一点。
答案 0 :(得分:0)
试试这个:
function eventListenerTest(event, callback) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, function (data) {
address = data.rows[0];
event.infoWindowHtml = "<b>Address: </b>" + address;
callback();
});
}
}
然后:
eventListenerTest(event, function(){
// you will use updated event object here
});
答案 1 :(得分:0)
您应该使用$ .proxy方法来确保执行的回调函数保持函数的上下文创建Ajax调用。
更新了Javascript:
function eventListenerTest(event) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, $.proxy(function (data) {
address = data.rows[0];
event.infoWindowHtml = "<b>Address: </b>" + address;
},this));
}
}