<!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('单引号');" /> -------------------正确
本文详细介绍了JavaScript和HTML中单引号与双引号的使用规则,探讨了不同情境下如何正确使用引号避免语法错误,特别是针对HTML属性值内的JavaScript代码执行情况。
3万+





