javascript - document.write 的真正目的是什么?

标签 javascript html

<分区>

我正在尝试用 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上的语句必须在按钮下方。


结果:

提示框 显示时,我按下“接受”按钮,按钮消失,它只显示函数 document.write 上的句子。


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

Write some text directly to the HTML document

但我还可以看到另一个声明:

Using document.write() after an HTML document is fully loaded, will delete all existing 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 .

关于javascript - document.write 的真正目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833436/

相关文章:

html - 隐藏一个名为新加入者的组的 Div?

javascript - 具有嵌套属性的 HTML SetAttribute

php - 具有两个按钮的表单以不同的值提交

javascript - 要关闭菜单,我需要更改按钮的方向

html - Firefox/Chrome 上的字体大小和缩进不一致

html - Bootstrap 表单字段不会停留在包含 div 中

javascript - 在 v-for 循环中的每第 n 个项目之后插入项目

javascript - 到达网页上的特定位置时如何调用 css 动画?

javascript - 如何使用javascript for循环和if语句在右表中显示数据?

javascript - 当用户与站点交互时禁用自动滚动 'scrollToBottom' 功能