我遇到一个问题,尽管使用了 window.onload,但 document.getElementById 有时(10-20 次中有一次)返回 null。我的相关代码如下。
ptp.html:
<body>
<div msa-include-html="msa.html"></div>
<script type="text/javascript" src="msa.js"></script>
<script type="text/javascript">
includeHTML();
</script>
<script type="text/javascript">
window.onload = function () {
initForm("urlAction");
}
</script>
</body>
msa.html:
<form id="msa" method="get">
<input id="input" type="text" name="input" />
<p id="output"></p>
<input id="btn" type="submit" value="SUBMIT" />
</form>
msa.js:
includeHTML = function (cb) {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("msa-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
elmnt.innerHTML = this.responseText;
elmnt.removeAttribute("msa-include-html");
includeHTML(cb);
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
if (cb) cb();
};
function initForm(urlAction) {
document.getElementById("msa").action = urlAction;
document.getElementById("input").addEventListener("keyup", updateOutput);
}
function updateOutput() {
var input = document.getElementById("input").value;
var output = Number((1 / 3 * input).toFixed(0));
document.getElementById("output").innerHTML = output.toLocaleString();
}
提前非常感谢。
最佳答案
您的 includeHTML()
函数执行异步操作来获取内容。该函数将在该操作开始后返回,但提取将在您的其他代码期望其加载的内容出现在 DOM 中后完成。
线路
if (cb) cb();
应该位于 XHR 回调内部,而不是像现在这样位于外部。就目前而言,回调将在 HTTP 请求完成之前调用。我怀疑,您的代码仅当内容位于浏览器缓存中时才有效。
关于javascript - 尽管使用了 window.onload,但 document.getElementById 有时为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45326470/