JS来显示HTML标记

JS to show HTML tags

本文关键字:标记 HTML 显示 JS      更新时间:2023-09-26

例如,我有一个测试页面,如下所示:

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自动完成?

是的,我可以用&lt;&gt;手动替换<>,但我想避免手动工作。

尝试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;";
          }
    });
};

现在将值编码为

$( "#example" ).html( htmlEncode ( $( "#example" ).html() ) );

演示

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;";
    		  }
    	});
    };
    $( "#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>

这里已经回答了这个问题:是否有一种HTML/CSS方法可以在不进行解析的情况下显示HTML标记?

<style>
script
{
    display: block;
}
</style>
<div id="example">
    Then within document body:
<script type="text/plain">
    <p>Foo</p>
</script>
</div>

JSfiddle:https://jsfiddle.net/9vkowqb3/

检查以下jsfiddleHTML:

<p>This is how you should write paragraphs in HTML:</p>
<div id="example">
</div>

JS:

var text = document.createTextNode('<p>Stuff</p>');
document.getElementById('example').appendChild(text);