How can I display html tags inside an HTML document?

前端 未结 8 774
囚心锁ツ
囚心锁ツ 2020-12-10 04:16

I simply want to create something like that:

blah blah

I\'ve been trying to do this for a long time though for

相关标签:
8条回答
  • 2020-12-10 04:22

    You have to write stuff like &fdaf; because the browser refuses to believe that you mean <pre> for everything. This is the correct behavior, else how would you ever escape from a <pre> section? You have to go through the doc and for every less-than sign substitute &lt;. You do not have to do that for the greater-than sign or for ampersand (usually).

    0 讨论(0)
  • 2020-12-10 04:22

    to build on @mkluwe's answer, here is an example:

    <html>
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">        </script>
      </head>
      <body>
        <pre>
          <a href="http://localhost:3000/l/1/2/3" target="_blank">
            <img src="http://localhost:3000/b/1/2/3/4" target="_blank">
          </a>
        </pre>
        <script>
          $( 'pre' ).text( $( 'pre' ).html() );
        </script>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-12-10 04:23

    Use the <xmp> tag, e.g.

    <xmp>
      <html>
        <body>This is my html inside html.</body>
      </html>
    </xmp>
    

    You can also add styles and formatting inside <xmp> as well.

    0 讨论(0)
  • 2020-12-10 04:25

    The easiest way I know is to replace the < and > with &lt; and &gt; that way it's not html anymore. There are several other codes like these for & symbols, etc.

    Where is the text coming from? If it's in javascript than you're easiest way would be to do a regex replace in javascript.

    0 讨论(0)
  • 2020-12-10 04:28

    Don't use <xmp>, <plaintext> and <listing>. Use as suggested by MDN:

    Use the <pre> element or, if semantically adequate, the <code> element instead. Note that you will need to escape the < character as &lt; to make sure it is not interpreted as markup.

    0 讨论(0)
  • 2020-12-10 04:35

    Like mkluwe also said, you should use JavaScript (or a server-side script) to properly escape any user input. Here's another JavaScript function you could try:

    String.prototype.escapeHTML = function () {                                        
      return(                                                                 
        this.replace(/>/g,'&gt;').
             replace(/</g,'&lt;').
             replace(/"/g,'&quot;')
      );
    };
    var codeEl = document.getElementById('test');
    if (codeEl) {
      codeEl.innerHTML = codeEl.innerHTML.escapeHTML();
    }
    

    I haven't tested this in IE, but it should work there in theory. Here's a page where you can view the results: http://jsbin.com/oruri5/2/edit

    0 讨论(0)
提交回复
热议问题