繁体   English   中英

将JavaScript显示为代码段

[英]Display javascript as code snippet

我想做的是在页面上显示一段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代码段。 我在这里想念什么?

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

除现有的<pre>标记外,我还建议将代码包装在<code>标记中。

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

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

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

<script>...</script>

...您需要输入:

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

由于<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>

使用&lt;script&gt; &lt;/script&gt; 对于<script>标签

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