在教程中,我学会了使用document.write. 现在我明白很多人不赞成这样做。我试过print(),但后来它确实将它发送到打印机。
那么我应该使用哪些替代方案,为什么我不应该使用document.write?w3schools 和 MDN 都使用document.write.
在教程中,我学会了使用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(), 和document.close()。加载 HTML 文档时,文档处于“打开状态”。  当文档完成加载时,文档已“关闭”。此时使用document.write()将删除您的整个(关闭的)HTML 文档并将其替换为一个新的(打开的)文档。这意味着您的网页已自行删除并开始编写新页面 - 从头开始。
我相信document.write()也会导致浏览器的性能下降(如果我错了,请纠正我)。
此示例在页面加载后将输出写入 HTML 文档。document.write()当您按下“消灭”按钮时,Watch的邪恶力量会清除整个文档:
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>
这是应该就地替换 document.write 的代码:
document.write=function(s){
    var scripts = document.getElementsByTagName('script');
    var lastScript = scripts[scripts.length-1];
    lastScript.insertAdjacentHTML("beforebegin", s);
}
您可以结合insertAdjacentHTML方法和document.currentScript属性。
insertAdjacentHTML()Element 接口的方法将指定文本解析为 HTML 或 XML,并将结果节点插入到 DOM 树的指定位置:
'beforebegin': 在元素本身之前。'afterbegin': 就在元素内部,在它的第一个子元素之前。'beforeend': 就在元素内部,在它的最后一个子元素之后。'afterend': 在元素本身之后。该document.currentScript属性返回<script>当前正在处理其脚本的元素。最好的位置是beforebegin —— 新的 HTML 将被插入到<script>它自己之前。为了匹配document.write的本机行为,可以将文本定位在afterend,但是随后对函数的连续调用的节点不会按照您调用它们的顺序放置(就像document.write那样),而是相反。HTML 出现的顺序可能比它们相对于<script>标签的位置更重要,因此使用beforebegin。
document.currentScript.insertAdjacentHTML(
  'beforebegin', 
  'This is a document.write alternative'
)
作为推荐的替代方案,document.write您可以使用DOM 操作直接查询节点元素并将其添加到 DOM。