Formatting this JavaScript Line

前端 未结 6 984
盖世英雄少女心
盖世英雄少女心 2020-12-22 01:02

I am trying to format this line of code in my popup window, but i am facing unterminated string literal error.

Can somebody please tell me how best I co

相关标签:
6条回答
  • 2020-12-22 01:12

    Best not to use a string, but an anonymous function instead:

    window.setTimeout(function () {
        winId.document.write(
          '<script src="../js/tiny_mce/tiny_mce.js" type="text/javascript"></script>\n'
        );
    }, 10);
    

    Using strings in setTimeout and setInterval is closely related to eval(), and should only be used in rare cases. See http://dev.opera.com/articles/view/efficient-javascript/?page=2

    It might also be worth noting that document.write() will not work correctly on an already parsed document. Different browsers will give different results, most will clear the contents. The alternative is to add the script using the DOM:

    window.setTimeout(function () {
        var winDoc = winId.document;
        var sEl = winDoc.createElement("script");
        sEl.src = "../js/tiny_mce/tiny_mce.js";
        winDoc.getElementsByTagName("head")[0].appendChild(sEL);
    }, 10);
    
    0 讨论(0)
  • 2020-12-22 01:15

    It's because you're using nested double quotes. Quotes delimit strings so when you get to the second one, it thinks the string has ended, as you can see from the colour highlighting in the code you posted. You need to escape them with \":

    window.setTimeout("winId.document.write('<script src=\"../js/tiny_mce/tiny_mce.js\" type=\"text/javascript\"></script>\n')", 10);
    
    0 讨论(0)
  • 2020-12-22 01:18

    Aside from you needing to escape your quotes (as other people have mentioned), you cannot include "</script>" (even if it's within a string) anywhere within a <script> tag

    Use:

    window.setTimeout(function () {
        winId.document.write(
          '<script src="../js/tiny_mce/tiny_mce.js" type="text/javascript"></scr' + 'ipt>\n'
        );
    }, 10);
    

    Instead.

    0 讨论(0)
  • 2020-12-22 01:23

    You can use this online tool: http://jsbeautifier.org/ best regards

    0 讨论(0)
  • 2020-12-22 01:31

    You may try it by escaping the double-quotes and <>, as well as \n:

    window.setTimeout("winId.document.write('\<script src=\"../js/tiny_mce/tiny_mce.js\" type=\"text/javascript\"\>\</script\>\\n')", 10);
    
    0 讨论(0)
  • 2020-12-22 01:34

    You have to escape the " in your script tag attributes with \" so it would read:

    window.setTimeout("winId.document.write('<script src=\"../js/tiny_mce/tiny_mce.js\" type=\"text/javascript\"></script>\n')", 10);
    
    0 讨论(0)
提交回复
热议问题