例如,我有一个这样的测试页面:
index.html:
<p>This is how you should write paragraphs in HTML:</p>
<div id="example">
<p>Foo</p>
</div>
如果我在浏览器中打开此页面,我想同时看到文本和标签:
This is how you should write paragraphs in HTML:
<p>Foo</p>
如何用js自动完成?
是的,我可以手动替换<
和>
通过<
和>
,但我想避免手动工作。
最佳答案
尝试 htmlEncode
方法为
function htmlEncode ( html )
{
html = $.trim(html);
return html.replace(/[&"'\<\>]/g, function(c)
{
switch (c)
{
case "&":
return "&";
case "'":
return "'";
case '"':
return """;
case "<":
return "<";
default:
return ">";
}
});
};
现在将值编码为
$( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );
演示
function htmlEncode ( html )
{
html = $.trim(html);
return html.replace(/[&"'\<\>]/g, function(c)
{
switch (c)
{
case "&":
return "&";
case "'":
return "'";
case '"':
return """;
case "<":
return "<";
default:
return ">";
}
});
};
$( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is how you should write paragraphs in HTML:</p>
<div id="example">
<p>Foo</p>
</div>
关于javascript - JS 显示 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37118381/