javascript innerHTML 和使用 createTextNode 填充跨度之间有什么主要区别吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13122760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there any major difference between innerHTML and using createTextNode to fill a span?
提问by Jeff Noel
The title is pretty clear:
Is there any major difference between innerHTML
and createTextNode
(used with Append
) to fill a span with text?
标题很清楚:innerHTML
和createTextNode
(与 一起使用Append
)用文本填充跨度之间有什么主要区别吗?
回答by Bergi
Of course. createTextNode
will escape any strings and show them as they are, while innerHTML
could render html-like strings into a DOM. If you don't want that (unless you are sure the text contains no unescaped tags, e.g. when assigning a literal directly), you can use textContent
(or innerText
for IE).
当然。createTextNode
将转义任何字符串并按原样显示它们,同时innerHTML
可以将类似 html 的字符串渲染到 DOM 中。如果您不希望那样(除非您确定文本不包含未转义的标签,例如直接分配文字时),您可以使用textContent
(或innerText
用于 IE)。
Yet I'd recommend createTextNode
, because all browsers support it equally without any quirks.
但我推荐createTextNode
,因为所有浏览器都同样支持它,没有任何怪癖。
回答by jeesty
My understanding is that certain manipulations of innerHTML remove all bound events, so using createTextNode is preferable.
我的理解是,innerHTML 的某些操作会删除所有绑定事件,因此最好使用 createTextNode。
回答by venkat0591
Doing some research online, here's what I've found. This should cover it at a high level:
在网上做了一些研究,这是我发现的。这应该在高层次上涵盖它:
elem.createTextNode(text) and elem.textContent= text do the exact same thing (src: https://javascript.info/task/createtextnode-vs-innerhtml)
While textContentreturns the full text contained in a node, innerTextreturns only the visible text contained in the node. (src: Difference between textContent vs innerText)
元素。createTextNode(文本)和 elem。textContent= text 做同样的事情(源代码:https: //javascript.info/task/createtextnode-vs-innerhtml)
而的textContent返回包含在节点中的全文,innerText属性只返回可见文本包含在这个节点。(src:textContent 与 innerText 之间的区别)