简体   繁体   中英

How to format JavaScript code snippet to display on Web Page?

I am trying to format JavaScript code snippet to display on a web page as follow:-

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

I got the clue from this SO Link .

I have included all the files and followed the instrucntion but its not formatting it rather showing the snippet as combined.

Here is a screen shot在此处输入图片说明

I am getting the code from json file that is why it is in a single line.

I have removed the <script> and the result is same.

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

Any clue how may I intend it properly ?

If you wish to show the indents, you need to format the content in a multi-line string.

 document.getElementById('src').textContent = ` $(document).ready(function(){ setTimeout(function(){ console.log('deleting cookie'); $.cookie('cookie',null,{domain: document.domain}); },1000); }); `;
 <pre class="prettyprint"> <code class="javascript" id="src"></code> </pre>

BTW, please do not use document.getElementById('src').innerHTML = xxx , since <script> inside the string would be valid javascript code and would be executed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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