Javascript JS来显示HTML标记
例如,我有这样一个测试页面: index.html:Javascript JS来显示HTML标记,javascript,jquery,Javascript,Jquery,例如,我有这样一个测试页面: index.html: <p>This is how you should write paragraphs in HTML:</p> <div id="example"> <p>Foo</p> </div> 这是您应该如何用HTML编写段落: 福 如果在浏览器中打开此页面,我希望同时看到文本和标记: This is how you should write paragraph
<p>This is how you should write paragraphs in HTML:</p>
<div id="example">
<p>Foo</p>
</div>
这是您应该如何用HTML编写段落:
福
如果在浏览器中打开此页面,我希望同时看到文本和标记:
This is how you should write paragraphs in HTML:
<p>Foo</p>
这是用HTML编写段落的方法:
福
如何使用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 ">";
}
});
};
演示
函数htmlEncode(html)
{
html=$.trim(html);
返回html.replace(/[&“\]/g,函数(c)
{
开关(c)
{
案例“&”:
返回“&;”;
案例“'”:
返回“';”;
案例'':
返回“”;
案例“这里已经回答了这个问题:
剧本
{
显示:块;
}
然后在文档体中:
福
jsIDLE:检查以下内容
HTML:
这是您应该如何用HTML编写段落:
JS:
var text=document.createTextNode(“Stuff”);
document.getElementById('example').appendChild(text);
可能会让您感兴趣您是否仍然希望
-Tag成为
-Tag(如
)?
$( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );
<style>
script
{
display: block;
}
</style>
<div id="example">
Then within document body:
<script type="text/plain">
<p>Foo</p>
</script>
</div>
<p>This is how you should write paragraphs in HTML:</p>
<div id="example">
</div>
var text = document.createTextNode('<p>Stuff</p>');
document.getElementById('example').appendChild(text);