<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
//全局函数直接调用,不需要对象来调用
var s = "alert('1')";//alert窗口输出1
var s = 'alert("1")';//alert窗口输出1
eval(s);//计算JavaScript字符串,并把它作为脚本代码来执行
</script>
</head>
<body>
</body>
</html>
JS中的单引号和双引号其实没啥区别,看你自己习惯了。但若双引号中再使用双引号,我们可采取"外双内单"或者"外单内双"的格式;如果需要的是双引号本身,则只能是"外单内双":
HTML中的单引号与双引号很简单,就是两个字符实体:
显示 描述 实体名称 实体编号
" 双引号、引号 " "
' 单引号、撇号 ' '
x
1
显示 描述 实体名称 实体编号
2
" 双引号、引号 " "
3
' 单引号、撇号 ' '
JS中的单引号和双引号其实没啥区别,看你自己习惯了。
但若双引号中再使用双引号,我们可采取
"外双内单"
或者
"外单内双"
的格式;如果需要的是双引号本身,则只能是"外单内双":
console.log("包'青'天"); //包'青'天
console.log('包"青"天'); //包"青"天
console.log("包"青"天"); //错误
x
1
console.log("包'青'天"); //包'青'天
2
console.log('包"青"天'); //包"青"天
3
console.log("包"青"天"); //错误
或者像JAVA中那样,用 反斜杠\ 来禁止解析双引号:
console.log("包\"青\"天"); //包"青"天
1
console.log("包\"青\"天"); //包"青"天
一个容易混淆的地方
比如在一个网页中的按钮,写onclick事件的处理代码,不小心写成如下:
<input type="button" onclick="alert("弹窗")" /> -------------------不正确
1
<input type="button" onclick="alert("弹窗")" /> -------------------不正确
提示出错后,再漫不经心地改为:
<input type="button" onclick="alert(\"弹窗\")" /> ----------------不正确
1
<input type="button" onclick="alert(\"弹窗\")" /> ----------------不正确
结果还是出错。这时,我就想不通了,虽然我知道最直接的解决方法是写成这样:
<input type="button" onclick="alert('弹窗')" /> -------------------正确
<input type="button" onclick='alert("弹窗")' /> -------------------正确
1
<input type="button" onclick="alert('弹窗')" /> -------------------正确
2
<input type="button" onclick='alert("弹窗")' /> -------------------正确
但为什么JS中的转义字符 \ 没有效果了呢?
这是因为,这段代码还是归于HTML的管辖范围,所以转义字符应该使用HTML的,而不是javascript的:
<input type="button" onclick="alert("双引号");" /> -------------------正确
<input type="button" onclick="alert("双引号");" /> -------------------正确,【"】和【"】没任何区别
<input type="button" onclick="alert('单引号');" /> -------------------正确
1
<input type="button" onclick="alert("双引号");" /> -------------------正确
2
<input type="button" onclick="alert("双引号");" /> -------------------正确,【"】和【"】没任何区别
3
4
<input type="button" onclick="alert('单引号');" /> -------------------正确