在教程中,我学会了使用document.write
。现在我明白了,很多人都不赞成这样做。我试过print()
,但它会直接把它发送到打印机。
那么我应该使用什么替代方案,为什么我不应该使用document.write
呢?w3schools和MDN都使用document.write
。
发布于 2010-12-27 18:15:35
作为document.write
的推荐替代方案,您可以使用DOM manipulation直接查询节点元素并将其添加到DOM中。
发布于 2014-12-18 01:14:42
替换HTML的原因是因为一个邪恶的JavaScript函数:。
这绝对是“糟糕的形式”。如果你在页面加载时使用它,它只适用于网页;如果你在运行时使用它,它将用输入替换整个文档。如果您将其作为严格的XHTML结构应用,那么它甚至不是有效的代码。
问题是:
document.write
写入文档流。在已关闭(或已加载)的文档上调用document.write
会自动调用document.open
,这将清除文档。
document.write()
有两个追随者document.open()
和document.close()
加载HTML文档时,文档是“打开”的。当文档加载完成时,文档已经“关闭”。此时使用document.write()
的将擦除整个(关闭的)文档,并将其替换为一个新的(打开的)文档。这意味着你的网页已经擦除了自己,并开始从头开始写一个新的页面。
我相信也会导致浏览器性能下降(如果我错了,请纠正我)。
举个例子:
此示例在加载页面的之后将输出写入HTML文档。当你按下“清除”按钮时,观看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>
发布于 2013-11-04 04:28:47
下面是应该替代document.write的代码:
document.write=function(s){
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
lastScript.insertAdjacentHTML("beforebegin", s);
}
https://stackoverflow.com/questions/4537963
复制相似问题