document.write()有没有错误? [英] Is there any bug with document.write()?

查看:69
本文介绍了document.write()有没有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是这样的:

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.

像这样:

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.

所以,我写'AAA'来检查< br> 代码是否已添加。

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

喜欢这样:

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")
}

有一个新行,和AAA。

There's a new line, and AAA.

所以,我认为有一个错误或 document.write()

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

有没有错误?

或者我写错了什么?

我的目的是添加一个新行。

My purpose is to add a new line.

我想让我的代码正常运行。

I want to make my code run properly.

有没有办法解决这个问题?

Is there any way to solve this problem?

推荐答案

问题是,如果页面已经加载, document.write 将使用新的HTML字符串替换整个页面。如果你删除了 window.onload 处理程序,只要浏览器进入< script> 标签,< input> < br> 将按预期插入到文档中:

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>

一般来说,解决方法是使用 document.write - 它的行为可能令人困惑,并且它提供的任何东西都不能使用 appendChild insertAdjacentHTML 等方法轻松完成,例如:

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

document.body.insertAdjacentHTML('beforeend', '<br>');

这篇关于document.write()有没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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