简体   繁体   中英

Javascript code inside var

I need to add some HTML and Javascript code inside a javascript variable to write them later in my .html page

example of what i tried to write in my Javascript page

var footer = "<footer><script>
if(isMobile.any()){
document.write('<a href="twitter:///user?screen_name=twitter">');
} else {
    document.write('<a href="https://twitter.com/twitter">');
}</script></footer>";

and the way im writing it in my HTML document

<script>document.write(footer);</script>

but im getting errors inside my javascript page caused by the javascript code inside the variable

sorry i'm new in javascript and thanks in advance

Strings can't go across multiple lines without proper handling; embedded quotes need to be escaped too; this is by no means the cleanest way, but one suggestion could be:

var footer = 
  "<footer><script>" +
    "if(isMobile.any()) {" +
      "document.write('<a href=\"twitter:///user?screen_name=twitter\">');" +
    "} else {" +
      "document.write('<a href=\"https://twitter.com/twitter\">');" +
  "}" +
  "</script></footer>";

Also note that you use document.write inside script tags, when your literal script string has that tag. You need it for that piece of script, but you might consider your overall output.

You need to escape the quotes( " ) inside the string like \\" :

var footer = "<footer><script>
if(isMobile.any()){
document.write('<a href=\"twitter:///user?screen_name=twitter\">');
} else {
    document.write('<a href=\"https://twitter.com/twitter\">');
}</script></footer>";
var footer = "<footer><script>
if(isMobile.any()){
document.write('<a href='twitter:///user?screen_name=twitter'>');
} else {
document.write('<a href='https://twitter.com/twitter'>');
}</script></footer>";

as another answer already pointed out, when the second double qute is encountered, it's considered as the end if the string, you've to either escape it, or use single quotes throughout the string, as above.

This is a slight modification to @Grant Thomas's answer

var footer = "<footer>\x3Cscript>\
   if(isMobile.any()){\
     document.write('<a href=\"twitter:///user?screen_name=twitter\">');\
   } else {\
    document.write('<a href=\"https://twitter.com/twitter\">');\
   }\x3C/script></footer>";

You can read up about why you need to use \\x3c here Link

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