1.JS简介
(1)JS的基本输出语句
实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
document.write("<p>this is javascript</p>");
</script>
</body>
</html>
(2)JS对事件作出反应
具体实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button type="button" onclick="alert('Welcome!')">点我</button>
</body>
</html>
上述代码中onclick为事件属性
alert()函数为自带的警报函数,在测试代码中会经常用到
(3)JS改变html内容
实例如下
v<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p id="test">不要改变我!</p>
<script>
function myFunction() {
x = document.getElementById('test'); //寻找元素
x.innerHTML = '我就要改变你!'; //改变元素
}
</script>
<button type="button" onclick="myFunction()">点我</button>
</body>
</html>
(4)JS验证输入
实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<p>请输入账号</p>
<input id="test" type="text">
<script>
function myFunction() {
var x = document.getElementById('test').value;
if(x == '' || isNaN(x)) //为空或者不是数字
{
alert('Not Numeric');
}
}
</script>
<button type="button" onclick="myFunction()">登陆</button>
</body>
</html>
2.JS中的变量
(1)JS变量定义前有个var
实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var pi = 3.14;
var name = 'jesse';
document.write(pi + "<br>");
document.write(name)
</script>
</body>
</html>
(2)数组的使用
实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var arr = new Array();
arr[0] = 1;
arr[1] = 2;
document.write(arr[0] + "<br>");
document.write(arr[1] + "<br>")
</script>
</body>
</html>
(3)对象的使用
实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var Me = {firstname:'miao',lastname:'shuai'};
document.write(Me.firstname)
document.write(Me.lastname)
</script>
</body>
</html>
3.JS中的循环
JS中for循环使用如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
var arr = new Array(1,2,3,4,5,6);
for(var i = 0; i < arr.length; i++)
{
document.write(arr[i] + "<br>")
}
</script>
</body>
</html>
4.JS中的错误处理
实例如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
try
{
allert('函数名未定义');
}
catch(err)
{
var txt = 'this is an err' + err.message;
alert(txt);
}
</script>
</body>
</html>