什么时候应该使用.innerHTML和JavaScript中的document.write [英] When should one use .innerHTML and when document.write in JavaScript
问题描述
是否有一般规则,当人们应该使用 document.write
更改网站内容以及何时使用 .innerHTML
?
Is there a general rule, when one should use document.write
to change the website content and when to use .innerHTML
?
到目前为止,我的规则是:
So far my rules were:
1)使用文件.write
添加新内容时
2)使用 .innerHTML
当更改现有内容时
2) Use .innerHTML
when changing existing content
但我很困惑,因为有人告诉我,一方面。 innerHTML
是一个奇怪的Microsoft标准,但另一方面我读到XHTML中不允许 document.write
。
But I got confused, since someone told me that on the one hand .innerHTML
is a strange Microsoft standard, but on the other hand I read that document.write
is not allowed in XHTML.
我应该使用哪些结构来操纵我的源代码?
Which structures should I use to manipulate my source code with JavaScript?
推荐答案
innerHTML
可用于通过字符串munging来更改DOM的内容。因此,如果你想在所选元素的末尾添加一个带有一些文本的段落,你可以像
innerHTML
can be used to change the contents of the DOM by string munging. So if you wanted to add a paragraph with some text at the end of a selected element you could so something like
document.getElementById('some -id').innerHTML + ='< p>这里有一些文字< / p>'
虽然我建议使用尽可能多的DOM操作特定API(例如 document.createElement
, document.createDocumentFragment
, < element> .appendChild
等)。但这只是我的偏好。
Though I'd suggest using as much DOM manipulation specific API as possible (e.g. document.createElement
, document.createDocumentFragment
, <element>.appendChild
, etc.). But that's just my preference.
我唯一一次看到适用的 document.write
就在 HTML5 Boilerplate (看看它如何检查jQuery是否正确加载)。除此之外,我会远离它。
The only time I've seen applicable use of document.write
is in the HTML5 Boilerplate (look at how it checks if jQuery was loaded properly). Other than that, I would stay away from it.
这篇关于什么时候应该使用.innerHTML和JavaScript中的document.write的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!