Javascript 将 HTML 编码的字符串附加为 HTML,而不是文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8437352/
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-08-24 06:00:56  来源:igfitidea点击:

Appending HTML-encoded string as HTML, not as text

javascriptjqueryhtmlappend

提问by zakdances

I'm trying to append this string:

我正在尝试附加此字符串:

<div> hello </div>

as an HTML node, but instead of appending HTML it just appends the text:

作为一个 HTML 节点,但它只是附加文本而不是附加 HTML:

<div> hello </div>

How do I make jQuery append this as an HTML node, not just text?

如何让 jQuery 将其附加为 HTML 节点,而不仅仅是文本?

I'd like a solution that works both for nested divs AND text, if possible.

如果可能的话,我想要一个既适用于嵌套 div 又适用于文本的解决方案。

回答by Timothy Khouri

// This is your string :)
var myString = "&lt;div&gt; hello &lt;/div&gt;";

// This is a way to "htmlDecode" your string... see link below for details.    
myString = $("<div />").html(myString).text();

// This is appending the html code to your div (which you don't have an ID for :P)
$("#TheDivIWantToChange").append(myString);

HTML-encoding lost when attribute read from input field

从输入字段读取属性时 HTML 编码丢失

回答by Kevin M

You can create a new div with .createElement('div'). Then simply change the new element's HTML.

您可以使用.createElement('div'). 然后只需更改新元素的 HTML。

$(document.createElement('div').html('<p>All new content.</p>'));

To attach the new element to the DOM either use element.append()or .appendTo(element)to append to your element of choice.

要将新元素附加到DOM,请使用element.append().appendTo(element)附加到您选择的元素。

回答by jamesmillerio

Maybe this is a bit verbose, but this is usually how I handle stuff like that:

也许这有点冗长,但这通常是我处理类似事情的方式:

var div = $(document.createElement("div"));

div.text(" hello "); //Or div.html(" hello ") if need be...

$("#divtoappendto").append(div);