JavaScript 等待文件
如果您创建函数来加载外部资源(如脚本或文件),则在内容完全加载之前无法使用这些内容。
这是使用回调的最佳时机。
此例加载一个 HTML 文件 (mycar.html),并在文件完全加载后在网页中显示该 HTML 文件:
等待文件:
function myDisplayer(some) {
document.getElementById("demo")。innerHTML = some;
}
function getFile(myCallback) {
let req = new XMLHttpRequest();
req.open('GET', "mycar.html");
req.onload = function() {
if (req.status == 200) {
myCallback(this.responseText);
} else {
myCallback("Error: " + req.status);
}
}
req.send();
}
getFile(myDisplayer);
在上面的示例中,myDisplayer 用作回调。
函数(函数名)作为参数传递给 getFile()。
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64485.shtml