Is there any bug with document.write()?

霸气de小男生 提交于 2019-12-02 08:22:16

The problem is that, if the page has already loaded, document.write will replace the entire page with the new HTML string. If you removed your window.onload handler and simply had that snippet run as soon as the browser comes to the <script> tag, both the <input> and <br> would be inserted into the document as expected:

<script language="javascript">
  var x = document.createElement("INPUT");
  x.setAttribute("type", "text");
  x.setAttribute("value", "");
  document.body.appendChild(x);
  document.write("<br>");
</script>

Generally, the solution is to not use document.write - its behavior can be confusing, and it provides nothing that can't be accomplished just as easily with methods such as appendChild and insertAdjacentHTML, for example:

document.body.appendChild(document.createElement('br'));

or

document.body.insertAdjacentHTML('beforeend', '<br>');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!