为什么javascript没有加载document.readyState ===" complete"
我刚开始从 w3school 学习javascript,我找到了out你只能在HTML输出中使用document.write。如果在文档加载后使用它,整个文档将被覆盖。所以我试着写下面的代码来检查有效性:
I have just started learning javascript from w3school and I have found out that "You can only use document.write in the HTML output. If you use it after the document has loaded, the whole document will be overwritten." so I have tried to write following code to check the validity:
<html>
<head>
<title>ashish javascript learning</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p> sample html with javascript </p>
<script>
document.write("<h1>this is heading</h1>");
document.write("<p>this is sample para</p>");
</script>
<script>
if(document.readyState === "complete"){
loaded();
}
function loaded(){
document.write("<p>loading content after the document has been loaded");
}
</script>
</body>
</html>
代码仍然显示旧值,并且不会覆盖网页内容。你能告诉我我做错了什么吗?
Code is still showing the old value and is not overwriting the content of the web page. Could you suggest me what am I doing wrongly.
当你正在测试 document.readyState ===complete
,文件的readyState 不是完成,它是加载,所以没有任何反应,并且从未调用已加载
。
At the time you're testing document.readyState === "complete"
, the document's readyState isn't "complete", it "loading", so nothing happens, and loaded
is never called.
您可以侦听readyState进行更改,然后检查它是否完整(或收听 window.onload
这更容易):
You can listen for the readyState to change, and then check to see if it is "complete" (or listen to window.onload
which is easier):
document.onreadystatechange = function () {
if(document.readyState === "complete"){
loaded();
}
}