【问题标题】:Javascript: print html as plain text [duplicate]Javascript:将html打印为纯文本[重复]
【发布时间】:2017-08-28 20:38:16
【问题描述】:

我正在尝试从 javascript 打印纯 html,但不知道该怎么做。 示例:

$('#elem').html('This is a normal string'); // --> This is a normal string

$('#elem').html('This <b>contains</b> html')
//Current-> This contains html   (contains is bold)
//Wanted-> This <b>contains</b> html

我想这样做是因为我正在使用用户编写的 cmets,并且不希望 html 标签在他们将一些放入他们的 cmets 时应用。但由于其他原因,我需要查看标签。

感谢您的帮助!

【问题讨论】:

  • 使用.text而不是.html

标签: javascript html


【解决方案1】:

以下应该有效:

$('#elem').text('This <b>contains</b> html');

相关片段:

$('#an-id').text('&lt;b&gt;I don\'t want this to be HTML&lt;/b&gt;');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="an-id">This is not HTML!</p>

祝你好运!

查看jQuery documentation了解更多信息。

【讨论】:

    【解决方案2】:

    使用 jQuery .text() 函数,它会自动为您将 HTML 转义为文本!

    在这个例子中是:

    $('#elem').text('This <b>contains</b> html')
    

    【讨论】:

      【解决方案3】:

      你可以使用 jQuery .text() 方法。

      $('#elem').text('This <b>contains</b> html');
      

      示例:

      <!DOCTYPE html>
      <html>
      <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
      <script>
      $(document).ready(function(){
          $("button").click(function(){
              $("#elem").text('This <b>contains</b> html');
          });
      });
      </script>
      </head>
      <body>
      
      <button>Click ME!!</button>
      
      <p id="elem">This is a paragraph.</p>
         
      </body>
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-20
        • 2017-03-20
        • 1970-01-01
        • 2020-03-25
        • 2014-09-24
        • 1970-01-01
        • 1970-01-01
        • 2015-01-03
        相关资源
        最近更新 更多