javascript - 未捕获的语法错误 : Unexpected token ILLEGAL - A simple string syntactically wrong

标签 javascript string variables

为什么这个看似简单的字符串变量在语法上是错误的?

var str = "<script>functionName()</script>";

我收到以下错误

Uncaught SyntaxError: Unexpected token ILLEGAL

这是fiddle

最佳答案

打开控制台并尝试输入字符串

var str = "<script>functionName()</script>";

没有语法错误,一切正常。

当您将代码嵌入到脚本标记中时,如下所示

<script>
// code here
</script>

在 JSFiddle 中,如果您检查错误,您将看到类似的内容

<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var str = "<script>functionName()</script>";
}//]]> 

</script>

浏览器不允许</将字符串嵌入 <script> 时,字符串中的字符标签。

因此,您需要使用 \ 来转义它

关于javascript - 未捕获的语法错误 : Unexpected token ILLEGAL - A simple string syntactically wrong,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395612/

相关文章:

javascript - PhoneGap登录页面,如何保存用户信息

javascript - wix/react-native-navigation V2 | wix/react-native-navigation V2 |在第二个屏幕中设置根底部选项卡

python - 提取一个 2 元素元组并将其转换为字符串

python - 如何使用原始输入来定义变量

javascript - AngularJS 从指令调用 Controller

c++ - 使用 C++ fmtlib,是否有比使用 std::ostringstream 更简洁的方法将数据序列 append 到字符串?

r - 迭代字符串 R 的字符

javascript - JavaScript 中的 "Variable"变量

java - 使用字符串值创建变量名

javascript - 我的 JavaScript 脚本不会在 php 中回显