简体   繁体   English

将JavaScript显示为代码段

[英]Display javascript as code snippet

What I'm trying to do is display a snippet of javascript on the page, and not have it run, just display as a code snippet for folks to copy. 我想做的是在页面上显示一段javascript,并且不运行它,而只是将其显示为供人们复制的代码段。 I load google's Prettify, then in the page I have this code: 我加载谷歌的Prettify,然后在页面中我有此代码:

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

But this code just executes and doesn't display the JS snippet. 但是此代码仅执行,不显示JS代码段。 What am I missing here? 我在这里想念什么?

You need to convert your < and > characters to HTML entities like so: 您需要像这样将<>字符转换为HTML实体:

<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. 除现有的<pre>标记外,我还建议将代码包装在<code>标记中。

The problem you have is that you are entering HTML and you want it to not be treated as HTML. 您遇到的问题是您正在输入HTML,并且希望它不被视为HTML。 Specifically, the opening <script> element. 具体来说,是开头的<script>元素。

In order to enter HTML that will not be parsed as HTML, you need to encode characters that are special to HTML. 为了输入不会被解析为HTML的HTML,您需要对HTML特有的字符进行编码。 For instance < is encoded as &lt; 例如, <编码为&lt; , > is encoded as &gt; >编码为&gt; , and & is encoded as &amp; ,并且&编码为&amp; .

So, to output the following without it being parsed as HTML: 因此,要输出以下内容而不将其解析为HTML:

<script>...</script>

...you need to enter: ...您需要输入:

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

It's running because of the <script> tags. 由于<script>标记,它正在运行。 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; 使用&lt;script&gt; and &lt;/script&gt; &lt;/script&gt; for <script> tag 对于<script>标签

Let the textContent property (or createTextNode ) do all the heavy lifting of encoding whatever text you need to insert into dom: textContent属性(或createTextNode )完成所有createTextNode的编码工作,无论您需要插入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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM