Javascript 如何从jquery中的字符串获取Raw html?

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

How to get Raw html from string in jquery?

javascriptjqueryhtmlasp.net-mvc-3html-encode

提问by kheya

I have <label class='ash'>Comment Removed</label>in the database.

<label class='ash'>Comment Removed</label>在数据库里。

When I show this on the grid. I get this on the page:

当我在网格上显示这个时。我在页面上得到了这个:

<label class='ash'>Removed</label>

Actually I should just get Removed in Gray color

实际上,我应该以灰色移除

How can I convert this to Html like I do in MVC 3 Razor view?

如何像在 MVC 3 Razor 视图中那样将其转换为 Html?

@Html.Raw(HttpUtility.HtmlDecode(comment.txt)) works fine

I am using jquery 1.6 on MVC 3

我在 MVC 3 上使用 jquery 1.6

I tried:

我试过:

$("<label class='ash'>Comment Removed</label>").html()
   unescape($(txt)).html()

May be it is simple, but can't figure it out

可能很简单,但想不通

采纳答案by Ender

This should do the trick for you:

这应该对你有用:

var elemString = $('<div/>').html("&lt;label class='ash'&gt;Comment Removed&lt;/label&gt;").text();

Here's a demo showing it being appended to the body ->

这是一个演示,显示它被附加到主体 ->

If you need to do this multiple times, you could simplify with a function, like so:

如果您需要多次执行此操作,则可以使用一个函数进行简化,如下所示:

function DecodeHtml(str) {
    return $('<div/>').html(str).text();
}

var encodedStr = "&lt;label class='ash'&gt;Comment Removed&lt;/label&gt;";
$('body').append(DecodeHtml(encodedStr));