第一章 JavaScript简介
js脚本嵌入html网页,必须写在<script></script>标签里,但script具体位置不定,可在body里,可在head里,甚至可以放在二者之间。若出现多个script标签,解释从上到下遇到的第一个script标签里的js代码
1.2编写第一个js程序
1.2.1直接在html文件里写js代码
语法:<script language="javascript" >js代码</script>
eg:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>js脚本</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.33" />
</head>
<body>
<script language="javascript">
alert("Hello world!");
</script>
</body>
</html>
运行结果:
1.2.2导入js脚本文件
语法:<script language="javascript" src="js文件地址"></script>
eg:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>js脚本</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.33" />
</head>
<body>
<script language="javascript" src="firstjs.js"></script>
</body>
</html>
此时js文件里就一行代码:
alert("Hello world!");
运行结果同上:
1.2.3 注释
单行注释//
多行注释:/**/
js注释和C语言一样,尽管嵌套在html里,但仅在<script></script>标签里可用此注释,其他html位置,不可用
eg:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>js脚本</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.33" />
</head>
<body>
<script language="javascript">
//我是单行注释
alert("Hello world!");
/*
我是多行注释
*/
</script>
</body>
</html>
运行结果:
1.2.4 从不兼容的浏览器中隐藏js
可能一些老的浏览器不支持js脚本
两种处理方式隐藏js代码
方式1:
<!--html comment begin
alert("Hello World!");
//html comment end-->
方式2:
<NOSCRIPT>
The javascript code can not be execute.
</NOSCRIPT>
两种方式综合应用:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>js脚本</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.33" />
</head>
<body>
<script language="javascript">
<!-- html comment begin
alert("Hello world!");
//html comment end -->
</script>
<NOSCRIPT>
The javascript code can not be execute.
</NOSCRIPT>
</body>
</html>
1.2.7 调试js程序
以google浏览器为例
eg:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>js脚本</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.33" />
</head>
<body>
<script language="javascript">
alert("Hello world!";
</script>
</body>
</html>
运行无结果,按F12 打开开发者工具
右上角×表示有语法错误,并指出有几个语法错误
点×,下方会出现错误描述信息,即定位到错误的链接,点击方法右侧链接,定位到错误