Display javascript as code snippet

巧了我就是萌 提交于 2019-12-01 16:27:12

You need to convert your < and > characters to HTML entities like so:

<pre class="prettyprint">
  &lt;script&gt;
    $(document).ready(function(){
      setTimeout(function(){
        console.log('deleting cookie');
        $.cookie('cookie',null,{domain: document.domain});
      },1000);
    });
  &lt;/script&gt;
</pre>

I would also recommend wrapping the code in <code> tags in addition to the existing <pre> tags.

The problem you have is that you are entering HTML and you want it to not be treated as HTML. Specifically, the opening <script> element.

In order to enter HTML that will not be parsed as HTML, you need to encode characters that are special to HTML. For instance < is encoded as &lt;, > is encoded as &gt;, and & is encoded as &amp;.

So, to output the following without it being parsed as HTML:

<script>...</script>

...you need to enter:

&lt;script&gt;...&lt;/script&gt;

It's running because of the <script> tags. You should encode them:

<pre class="prettyprint">
&lt;script&gt;
$(document).ready(function(){
  setTimeout(function(){
    console.log('deleting cookie');
    $.cookie('cookie',null,{domain: document.domain});
 },1000);
});
&lt;/script&gt;
</pre>

use &lt;script&gt; and &lt;/script&gt; for <script> tag

Let the textContent property (or createTextNode) do all the heavy lifting of encoding whatever text you need to insert into dom:

var sampleCode="<script> $(document).ready(function(){ setTimeout(function(){ console.log('deleting cookie'); $.cookie('cookie',null,{domain: document.domain}); },1000); }); </script>";
var pre=document.createElement("pre");
pre.textContent=sampleCode;
pre.className="prettyprint";
document.body.appendChild(pre);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!