document.write 的替代品是什么?

2023-11-26

在教程中我学会了使用document.write。现在我明白,许多人对此不以为然。我试过了print(),但随后它实际上将其发送到打印机。

那么我应该使用什么替代方案,为什么我不应该使用document.write? w3schools 和 MDN 都使用document.write.


你的 HTML 被替换的原因是由于一个邪恶的 JavaScript 函数:document.write().

这绝对是“糟糕的形式”。仅当您在页面加载时使用它时,它才适用于网页;如果您在运行时使用它,它将用输入替换整个文档。如果您将其应用为严格的 XHTML 结构,那么它甚至不是有效的代码。


问题:

document.write写入文档流。呼唤document.write在关闭(或加载)的文档上自动调用document.open这将清除该文档。

-- 引用自MDN

document.write()有两个追随者,document.open(), and document.close()。当 HTML 文档加载时,文档处于“打开”状态。当文档加载完毕后,文档就“关闭”了。 Using document.write()此时将删除整个(关闭的)HTML 文档并将其替换为新的(打开的)文档。这意味着您的网页已自行擦除并开始从头开始编写新页面。

我相信document.write()也会导致浏览器性能下降(如果我错了,请纠正我)。


一个例子:

此示例将输出写入 HTML 文档after页面已加载。手表document.write()当您按下“消灭”按钮时,它的邪恶力量会清除整个文档:

I am an ordinary HTML page.  I am innocent, and purely for informational purposes. Please do not <input type="button" onclick="document.write('This HTML page has been succesfully exterminated.')" value="exterminate"/>
me!

替代方案:

  • .innerHTML这是一个很好的选择,但必须将此属性附加到要放置文本的元素。

例子:document.getElementById('output1').innerHTML = 'Some text!';

  • .createTextNode()是推荐的替代方案W3C.

例子:var para = document.createElement('p'); para.appendChild(document.createTextNode('Hello, '));

注意:众所周知,这会导致一些性能下降(慢于.innerHTML)。我建议使用.innerHTML反而。


的例子.innerHTML选择:

I am an ordinary HTML page. 
I am innocent, and purely for informational purposes. 
Please do not 
<input type="button" onclick="document.getElementById('output1').innerHTML = 'There was an error exterminating this page. Please replace <code>.innerHTML</code> with <code>document.write()</code> to complete extermination.';" value="exterminate"/>
 me!
<p id="output1"></p>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

document.write 的替代品是什么? 的相关文章