为什么javascript没有加载document.readyState ===" complete" [英] Why javascript is not loading for document.readyState==="complete"

查看:128
本文介绍了为什么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();
  }
}

这篇关于为什么javascript没有加载document.readyState ===&quot; complete&quot;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆