Using <pre> and <code> tags to display a javascript script

时间秒杀一切 提交于 2019-12-07 03:59:39

问题


I'm experimenting with the < pre> and < code> tags in html 5 as I would like to include some code snippets on my website. I'm using the page below as a test page but it is not displaying anything. Any reason why?

    <body>
    <div style="color:#000000">
      <pre>
        <code>
          <script type="text/javascript">
            $('#inputField').hide();
          </script>
        </code>
      </pre>
    </div>
    </body>

It was my understanding that using these new tags would negate any code that they contain within however this does not appear to be the case.

Cheers,

J


回答1:


These tags are only for "decorational" purposes. Code within will still be executed. If you want it displayed you have to convert at least the <script> tag to html:

&lt;script type="text/javascript"&gt;

Then the JavaScript code inbetween will be shown.

You don't need both though, I would use <pre> (which is per default a block element), <code> is intended for inline use.




回答2:


Remove script tag:

<body>
    <div style="color:#000000">
      <pre>
        <code>
            $('#inputField').hide();
        </code>
      </pre>
    </div>
</body>



回答3:


It was my understanding that using these new tags would negate any code that they contain

They don't. They tell user agents to present the data as code. So it will have font changes, white space will be significant, it should be skipped over by translation software and so on.

Markup still takes effect (so you can add elements to style, or link the code to other places, and so on) so you still need to replace HTML special characters (<, &, etc) with their respective entities (&lt;, &amp;, etc).




回答4:


This would work if you take the script tags out.

These code tags only change the font of the text inside to a monospace font, however it does not override the interpretation of other tags (or even php tags).

A better way is to use CSS to get color highlighting, or javascript libraries.



来源:https://stackoverflow.com/questions/17882167/using-pre-and-code-tags-to-display-a-javascript-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!