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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:52:29  来源:igfitidea点击:

Is there any major difference between innerHTML and using createTextNode to fill a span?

javascriptinnerhtmlcreatetextnode

提问by Jeff Noel

The title is pretty clear: Is there any major difference between innerHTMLand createTextNode(used with Append) to fill a span with text?

标题很清楚:innerHTMLcreateTextNode(与 一起使用Append)用文本填充跨度之间有什么主要区别吗?

回答by Bergi

Of course. createTextNodewill escape any strings and show them as they are, while innerHTMLcould 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 innerTextfor 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:

在网上做了一些研究,这是我发现的。这应该在高层次上涵盖它: