开发者

Formatting this JavaScript Line

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

Can somebody please t开发者_如何学Cell me how best I could format this.

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

Also point out if this particular line of code would work fine in the popup?


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);


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);


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.


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);


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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜