文档写入给出奇怪的输出 [英] Document write gives strange output

查看:82
本文介绍了文档写入给出奇怪的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来检测jQuery,如果它不存在则插入谷歌CDN版本和本地回退(不要问为什么......这不是我的想法),问题是当我尝试做document.write我得到一个奇怪的输出

I'm writing a script to detect jQuery, if it doesn't exist then insert the Google CDN version and a local fallback (don't ask why... it's not my idea), the problem is when I try to do document.write I get a strange output

document.write("<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"><\/script>')</script>");

输出应该来:

<script>window.jQuery || document.write('<script src="js/jquery.v1.9.1.js"></script>')</script>

但来到:

 <script>window.jQuery || document.write('<script src="js/jquery.v1.9.1.js"></script>"')"

无法弄清楚我的生活是否错误

can't figure out for the life of me whats wrong

推荐答案

基本上,发生的事情是当 document.write 打印出来时

Basically, what's happening is that when document.write prints out

<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"></script>')</script>

第一个< / script> 是被解析为实际的脚本结束标记,即使它在字符串内,导致类似

that first </script> is being parsed into the actual end-of-script tag, even though it's inside of a string, resulting in something like

<script>
    window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\">
</script>
')
</script>

字符串未结束(未终止的字符串文字),因为它的结束单引号现在不在脚本中,还有一个悬空的脚本结束标签。要阻止这种情况发生,你只需要像疯了一样逃避字符串中的脚本标记,特别是在字符串内的字符串中。下面是一个工作示例。

The string is not ended (unterminated string literal) because its closing single quote is now outside of the script, and there is also a dangling end-of-script tag. To stop this from happening, you simply need to escape like crazy the script tags inside the string, especially in the string inside the string. Below is a working example.

document.write("<script>window.jQuery || document.write('<script src=\"js/jquery.v1.9.1.js\"><\\\/script>')<\/script>");

这篇关于文档写入给出奇怪的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆