开发者

Why the JS codes inside pre or code block executes?

I have been trying to show some JS codes in a page.I have tried using

<pre >
    <code>
        <script type="text/javascript"> 
     开发者_如何学Python       $(function(){
                alert("Hello");
            });
        </script>
    </code>
</pre>

But if jQuery is loaded in the page then the I am getting an alert and the code is not being shown. How can i show this JS without executing the JS. I tried SyntaxHighLighter plugin and it's highlighting the code but still i am getting the alert.

What is the best way to show this JS code to users without executing them.


Because neither <pre> nor <code> mean "Don't treat this as markup".

<pre> means "Render whitespace here"

<code> means "Present this (i.e. use an appropriate font, etc) in such a way that it informs the reader that it is a code sample".

If you want to use characters which have special meaning in HTML (such as <) then you still have to use entities to represent them.

  • &lt; for <
  • &gt; for >
  • &amp; for &

You don't need to worry about ' or " as you aren't inside an attribute value.


Using <script> tags means that this is javascript to be executed.

Remove the <script> tags altogether:

<pre>
<code>
$(function(){
        alert("Hello");
    });
</code>
</pre>

Alternatively, encode the < and > to &lt; and &gt; so the <script> tags are rendered as text and not interpreted as script tags:

<pre>
<code>
&lt;script type="text/javascript"&gt;
$(function(){
        alert("Hello");
    });
&lt;/script&gt;
</code>
</pre>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜