Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS来显示HTML标记_Javascript_Jquery - Fatal编程技术网

Javascript JS来显示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

例如,我有这样一个测试页面:

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 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 "&amp;";
              case "'":
                return "&#39;";
              case '"':
                return "&quot;";
              case "<":
                return "&lt;";
              default:
                return "&gt;";
          }
    });
};
演示

函数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);