简体   繁体   English

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

[英]Appending HTML-encoded string as HTML, not as text

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和文本的解决方案。

// 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编码丢失

You can create a new div with .createElement('div') . 您可以使用.createElement('div')创建一个新的div。 Then simply change the new element's HTML. 然后只需更改新元素的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)追加到您选择的元素。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM