【问题标题】:JS to show HTML tags [duplicate]JS显示HTML标签[重复]
【发布时间】:2023-03-13 14:18:02
【问题描述】:

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

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

是的,我可以手动将&amp;lt;&amp;gt; 替换为&amp;lt;&amp;gt;,但我想避免手动工作。

【问题讨论】:

  • This 你可能会感兴趣
  • 您还希望&lt;p&gt;-Tag 成为&lt;p&gt;-Tag(如&lt;p&gt;&amp;lt;p&amp;gt; [...] &amp;lt;/p&amp;gt;&lt;/p&gt;)吗?

标签: javascript jquery


【解决方案1】:

尝试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>

【讨论】:

    【解决方案2】:

    这里已经回答了这个问题:Is there a HTML/CSS way to display HTML tags without parsing?

    <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/

    【讨论】:

      【解决方案3】:

      检查以下jsfiddle HTML:

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

      【讨论】:

        猜你喜欢
        • 2014-03-16
        • 2020-02-20
        • 2011-10-12
        • 1970-01-01
        • 2019-02-01
        • 1970-01-01
        • 2015-01-20
        • 2012-08-01
        相关资源
        最近更新 更多