如何将html转换为文本而不发表评论?

时间:2014-07-10 04:17:16

标签: jquery

假设我在html中有这个:

<code><?php die(); ?></code>

现在,我希望得到与<?php die(); ?>相同的结果,但它与html评论相符:

<!--?php die(); ?-->

$('code').text($('code').html());

demo

那么,现在我如何从文本中删除!----

2 个答案:

答案 0 :(得分:0)

使用 <pre>

<pre>&lt;?php die(); ?&gt;<pre>

或者

<code>&lt;?php die(); ?&gt;<code>

应该转义>,<,&

等字符

<强> Updated Demo

提示:您在问题中发布的代码(4个空格) - 通过检查元素了解Stack Overflow是如何做到的。

答案 1 :(得分:0)

你可以做点什么:

var c = $("code").contents().filter(function() {
    return this.nodeType == 8; //comment node
}).get(0).data;
//add '<' and '>', because they are replaced as part of comment by filter()
$("code").text("<" + c + ">"); //gives <?php die(); ?>

更新了Demo

相关问题