javascript - document.write错误? [英] javascript - document.write error?

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

问题描述

考虑脚本..

 < html> 
< head>
< script type =text / javascript>
document.write('TEST');
< / script>
< / head>

< body>
某些正文内容...
< / body>

< / html>

这很好,'TEST'这个词被添加到<

  < script type =text / javascript> 
window.onload = function(){
document.write('TEST');
}
< / script>

被使用,那么主体内容完全被'TEST'替换,即旧的主体内容被删除,并且只添加'TEST'这个词。


$ b

只有在 window.onload document.write 时才会发生这种情况c $ c> function

我在chrome中试过这个。我有没有犯过错误?任何建议?

解决方案

document.write()在文档完成分析并关闭后使用它。这种行为是不可预知的跨浏览器,你根本不应该使用它。改为使用 innerHTML createElement / createTextNode 来操作DOM。

Mozilla文档


在不调用document.open()的情况下写入已经加载的文档将自动执行document.open调用。一旦你完成了写作,建议调用document.close(),告诉浏览器完成加载页面。你写的文本被解析成文档的结构模型。在上面的例子中,h1元素成为文档中的一个节点。


$ b 如果document.write()调用直接嵌入到HTML代码中,那么它将不会调用document.open()。


等价的DOM代码将会是:

  window.onload = function(){
var tNode = document.createTextNode(TEST);
document.body.appendChild(tNode);
}


Consider the script..

<html>
<head>
   <script type="text/javascript">
        document.write('TEST');
   </script>
</head>

<body>
    Some body content ...
</body>

</html>

This works fine and the word 'TEST' is added to the <body>

But when

<script type="text/javascript">
    window.onload = function(){
        document.write('TEST');
    }
</script>

is used, then the body content is fully replaced by the word 'TEST' i.e, the old body contents are removed and ONLY the word 'TEST' is added.

This happens only when document.write is called within window.onload function

I tried this in chrome. Is there any mistake made by me ? any suggestions ?

解决方案

document.write() is unstable if you use it after the document has finished being parsed and is closed. The behaviour is unpredictable cross-browser and you should not use it at all. Manipulate the DOM using innerHTML or createElement/createTextNode instead.

From the Mozilla documentation:

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call. Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page. The text you write is parsed into the document's structure model. In the example above, the h1 element becomes a node in the document.

If the document.write() call is embedded directly in the HTML code, then it will not call document.open().

The equivalent DOM code would be:

window.onload = function(){
    var tNode = document.createTextNode("TEST");
    document.body.appendChild(tNode);
}

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

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