我有一个动态的页面,它由ajax调用填充,如下所示:
function loadpage() {
var container = document.querySelector(".container");
var xhr = new XMLHttpRequest();
xhr.open('GET', ("data.html"), true);
xhr.addEventListener("load", function(){
container.innerHTML = xhr.response;
var noticeBar = document.querySelector("#noticeBar"); //this is from data.html which was jsut loaded into the DOM.
});
xhr.send();
}
当我做类似的事情时:
function xyz(){
loadPage().
noticeBar.innerHTML = "bla bla bla"; //this will not work because the DOM hasnt been fully loaded
}
我正在寻找一种让它同步的方法。
答案 0 :(得分:0)
向loadpage()
添加回调参数:
function loadpage(callback) {
var container = document.querySelector(".container");
var xhr = new XMLHttpRequest();
xhr.open('GET', ("data.html"), true);
xhr.addEventListener("load", function(){
container.innerHTML = xhr.response;
var noticeBar = document.querySelector("#noticeBar"); //this is from data.html which was jsut loaded into the DOM.
callback(noticeBar);
});
xhr.send();
}
并传入回调函数:
function xyz(){
loadpage(
function(noticeBar) {
noticeBar.innerHTML = "blah blah blah";
}
);
}