8

我想要做的是在页面上显示一段 javascript,而不是让它运行,只是显示为代码片段供人们复制。我加载了谷歌的 Prettify,然后在页面中我有这个代码:

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

但是这段代码只是执行并且不显示 JS 片段。我在这里想念什么?

4

5 回答 5

14

您需要将您的<>字符转换为 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>

<code>除了现有标签之外,我还建议将代码包装在标签中<pre>

于 2013-07-19T18:42:22.453 回答
5

您遇到的问题是您正在输入 HTML,并且您希望它不被视为 HTML。具体来说,打开<script>元素。

为了输入不会被解析为 HTML 的 HTML,您需要对 HTML 特有的字符进行编码。例如<被编码为&lt;>被编码为&gt;&被编码为&amp;

因此,要输出以下内容而不将其解析为 HTML:

<script>...</script>

...您需要输入:

&lt;script&gt;...&lt;/script&gt;
于 2013-07-19T18:42:34.017 回答
2

由于<script>标签,它正在运行。您应该对它们进行编码:

<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>
于 2013-07-19T18:42:23.357 回答
0

使用&lt;script&gt;and &lt;/script&gt;for<script>标签

于 2013-07-19T18:42:33.423 回答
-1

textContent属性(或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);
于 2013-07-19T18:52:40.437 回答