将 HTML 编码的字符串附加为 HTML,而不是文本 [英] Appending HTML-encoded string as HTML, not as text

查看:19
本文介绍了将 HTML 编码的字符串附加为 HTML,而不是文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<div&gt;你好&lt;/div>

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

你好</div>

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

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

解决方案

//这是你的字符串 :)var myString = "<div>你好&lt;/div>";//这是一种对字符串进行htmlDecode"的方法...有关详细信息,请参见下面的链接.myString = $("

").html(myString).text();//这是将 html 代码附加到您的 div(您没有 :P 的 ID)$("#TheDivIWantToChange").append(myString);

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

I'm trying to append this string:

&lt;div&gt; hello &lt;/div&gt;

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

<div> hello </div>

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

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

解决方案

// 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 编码的字符串附加为 HTML,而不是文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆