Is it possible to include HTML code in JavaScript?

后端 未结 5 506
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 14:32

I have a basic question, can i include HTML code in JS? (with \"document.write\")

This is my HTML code:

    
  • 5条回答
    •  北荒
      北荒 (楼主)
      2021-02-04 15:25

      A different way of doing it is to put the HTML inside a script tag:

      
      

      Then you can get it into Javascript using

      var myHtml = document.getElementById('myHtml').innerHTML;
      

      or using one of several libraries which help you with this. Code inside a script tag with type="text/template" will not be interpreted or shown by the browser. The advantage of this approach over putting it straight into a string in Javascript is that it allows you to keep treating it as normal HTML in your editor, and it keeps the Javascript clean. See also this post by John Resig.

    提交回复
    热议问题