写文档的真正目的是什么?



我试图用JavaScript做一些证明,但我看到了一种行为,我认为它不必是这样的。下面是我的代码:

代码:

<!DOCTYPE html>
   <head>
       <meta charset = "utf-8"/>
       <title> Exercise prompt </title>
       <script type = "text/javascript">
          function disp_prompt()
          {
             var name = prompt("Please enter your name", "");
             
             if(name != null && name != "")
             {
                document.write("Hi " + name + " How are you?");
             }      
          }
       </script>
   </head>
   <body>
       <input type = "button" onclick = "disp_prompt()" value = "Show a prompt box." />
   </body>
</html>

预期结果:

当我点击按钮时,出现提示,当我点击"接受"按钮时,关于document.write功能的句子必须在按钮下方。


结果:

显示prompt box时,按下"接受"按钮,按钮消失,只显示document.write功能上的句子。


我可以在w3schools上看到下面的句子:

直接写一些文本到HTML文档

,但我也可以看到另一个语句:

在HTML文档完全加载后使用document.write(),将删除所有现有的HTML。

所以我无法理解document.write的真正目的。如果你想在你的HTML上写一些文字…为什么要移除剩下的元素?

是否有一种方法可以避免这种情况,并保持HTML上的其余元素?

提前感谢!

document.write()的目的是将一些动态/计算的内容插入到页面正好是脚本放置的位置。例如(虽然是人为的…):

<html>
<body>
  hello, the date is <script>document.write(new Date())</script>
</body>
</html>

一个更灵活的方法,让你修改页面内容后,它完全加载是使用一个专门的元素来承载你的内容,并改变它的innerHTML

function clicked() {
  document.getElementById('dynamic').innerHTML = 'It was clicked!';
}
<span onclick="clicked()">Click Me</span><br>
<span id="dynamic"></span>

除此之外,还有许多库可以帮助简化,最值得注意的是jQuery。

<html>
    <head>
        <meta charset = "utf-8"/>
        <title> Exercise prompt </title>
        <script type = "text/javascript">
            function disp_prompt()
            {
                var name = prompt("Please enter your name", "");
                if(name != null && name != "")
                {
                    document.getElementById("demo").innerHTML ="Hi " + name + " How are you?";
                }
            }
        </script>
    </head>
    <body>
        <button type = "button"  onclick = "disp_prompt()" >
            Show a prompt box.
        </button>
        <p id="demo">
        </p>
    </body>
</html>

最新更新