jQuery 将纯文本转换为 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14739537/
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
Convert plain text in to HTML
提问by Youss
I have a script with which at a certain point I'm getting HTML(data) with Ajax call. I have to turn this HTML in to plain text like this:
我有一个脚本,在某个时间点我通过 Ajax 调用获取 HTML(data)。我必须将此 HTML 转换为纯文本,如下所示:
$("#div").text(data);
I now want to turn this around and make the text HTML again. I there an easy Jquery method of doing this? I tried:
我现在想扭转这一局面并再次制作文本 HTML。我有一个简单的 Jquery 方法吗?我试过:
$("#div").text(data).end().html();
No luck.
没运气。
回答by Fenton
You would need to hold onto the original response to do this...
您需要保留原始回复才能执行此操作...
$("#hiddendiv").html(data);
$("#div").text(data);
Then you could get it back out...
那你可以把它取回来...
var html = $("#hiddendiv").html();
Update based on comment...
根据评论更新...
You can remove that element before you display it...
您可以在显示之前删除该元素...
var html = $(data);
$('#cookiediv', html).hide();
$('#div').html(html);
Where the cookie message has id="cookiediv"
- you may need to adjust the selector to get to this div, but it is almost certainly possible to grab it.
cookie 消息所在的位置id="cookiediv"
- 您可能需要调整选择器才能到达此 div,但几乎可以肯定会抓住它。
回答by Mike 'Pomax' Kamermans
The html function that you're using in your question can also take an argument. Read all about it here: http://api.jquery.com/html
您在问题中使用的 html 函数也可以带参数。在这里阅读所有相关信息:http: //api.jquery.com/html
Basically all you need to do is
基本上你需要做的就是
var div = $(yourdiv);
div.html(div.text())
such as in this example: http://jsfiddle.net/273Jx/
例如在这个例子中:http: //jsfiddle.net/273Jx/
回答by Popnoodles
If you mean take the text and make it working HTML. Working demo
如果您的意思是获取文本并使其工作 HTML。工作演示
<div id="div"></div>
jQuery:
jQuery:
var data='<a href="blah">blah</a>';
$('#div').text(data);
alert('ready...'); // just making you see the html
$('#div').html($('#div').text());
回答by Abdennour TOUMI
$.fn.toHtml=function(){
return $(this).html($(this).text())
}
then
然后
$('#div').toHtml()
回答by ajp15243
Try passing it directly to jQuery itself (http://api.jquery.com/jQuery/#jQuery2). It will take the raw HTML string and attempt to parse it into a new DOM fragment.
尝试将它直接传递给 jQuery 本身 ( http://api.jquery.com/jQuery/#jQuery2)。它将获取原始 HTML 字符串并尝试将其解析为新的 DOM 片段。