引入方式:
- 页头引入(head 标签内)
- 页中引入(body 标签内)
- 元素事件中引入(标签属性中引入)
- 引入外部 JS 文件
(<script type="text/javascript">……</script>
格式是固定的,JavaScript代码必须在<script></script>
标签内编写,并且必须设置type属性值 text/javascript 。)
(常用语句:document.write()
表示在页面输入某一内容)
元素事件中引入 JS:
1.直接编写:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input type="button" onClick="alert('绿叶学习网')" value="按钮"/>
</body>
</html>
2.调用JS函数:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function alertMessage()
{
alert("绿叶学习网");
}
</script>
</head>
<body>
<input type="button" onclick="alertMessage()" value="按钮"/>
</body>
</html>
引用外部文件:
<script src="js/index.js" type="text/javascript"></script>
变量的声明和赋值:
在 JS 中,所有的变量都由关键字 var 声明
变量类型有:number(数字)、string(字符串)、boolean(布尔判断)、null(空值)、undefined(未被定义、初始化的值)
typeof 运算符:
用于返回它的操作数当前所容纳的数据类型
(未被定义(初始化)的返回undefined)
如 typeof(1) 返回 number
类型转换:
字符串转数值型:parseInt() 和 parseFloat()
(3.14 转 int 后为 3)
数值转字符串:toString()
var n = parseFloat("3.14");
var str = n.toString + 999;
documate.write(n + "<br/>" + str);
// 3.14
// 3.14999
JS 语法:
语句的分号 “;” 是可有可无的。
documate.write();
显示
documate.getElementById()
Id 选择器,指定id调用,如:
document.getElementById("txt-ouput").value = unescape(str);
<body>
<textarea id="txt-ouput" cols="20"></textarea>
</body>
函数:
表达:
function 名字(参数1, 参数2)
{
// 语句
}
可以在事件响应中调用函数:
<input type="button" onclick="a()" value="提交"/>
或者超链接中:
<a href="javascript:a()"></a>
部分内置函数:
isNaN() 函数:
功能:判断是否是数字值,不是返回 true, 是返回 false
如:
123 false
“123” false (字符串类型的数字会被自动转换为数字型)
“abc123” true
escape 函数与 unescape 函数:
escape :对字符串编码,使其在所有机器上可读
umescape :解码