Is there any bug with document.write()?

六月ゝ 毕业季﹏ 提交于 2020-01-30 10:34:12

问题


I had my code something like this:

window.onload = function() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "");
    document.body.appendChild(x);
}

And I wanted to write something more, I added a new line.

Like this:

window.onload = function() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "");
    document.body.appendChild(x);
    document.write("<br>");
}

And then, suddenly, my input tag disappeared.

So, I wrote 'AAA'to check whether the <br> code was added or not.

Like this:

window.onload = function() {
    var x = document.createElement("INPUT");
    x.setAttribute("type", "text");
    x.setAttribute("value", "");
    document.body.appendChild(x);

    document.write("<br>");
    document.write("AAA")
}

There's a new line, and AAA.

So, I think there's an bug or something with document.write().

Is there any bug?

Or did I write something wrong?

My purpose is to add a new line.

I want to make my code run properly.

Is there any way to solve this problem?


回答1:


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>');


来源:https://stackoverflow.com/questions/53246198/is-there-any-bug-with-document-write

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