1 JavaScript引入方式
1.1 内部脚本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试JavaScript</title>
</head>
<body>
<script>alert("hello boy!")</script>
</body>
</html>
效果
1.2 外部引入
main.html
<script src="../js/main.js"></script>
main.js
alert("hello js");
目录结构
2 JavaScript语法
2.1 输出
输出到html
document.write("hello my sweaty!");
输出到控制台
console.log("this is a log");
查看日志
2.2 变量
//用var声明变量
var test = 20;
//变量可以存放不同类型的值
test = "张三"
//使用let定义的变量不可重复声明
let id = 20;
// let id = "张三";//Uncaught SyntaxError: Identifier 'id' has already been declared (at main.js:14:5)
//const定义常量不可改变
const VALUE = 10;
//VALUE = 20;//Attempt to assign to const or readonly variable
2.3 数据类型
var age = 30;
var price = 34.5;
var name = "刘邦";
var valid = true;
var obj = null;
var testUndefine;
console.log("typeof age = " + typeof age)
console.log("typeof name = " + typeof name)
console.log("typeof valid = " + typeof valid)
console.log("typeof obj = " + typeof obj)
console.log("typeof testUndefine = " + typeof testUndefine)
结果输出
this is a log
main.js:34 typeof age = number
main.js:35 typeof name = string
main.js:36 typeof valid = boolean
main.js:37 typeof obj = object
main.js:38 typeof testUndefine = undefined
2.4 运算符
2.4.1==和===的区别
var number1 = 30;
var number2 = "30";
//==和===的区别
console.log(number1 == number2);
console.log(number1 === number2);
输出结果
true
false
2.4.2 类型转换
var number3 = +"40";
console.log(number3 + 1);
console.log(parseInt(number3) + 1);
var flag = +false;
console.log("flag = " + flag);
//number类型转换为boolean类型,0和nan转化为false,其他数字转为true
//string类型转换为boolean类型,空字符串为false,其他字符串转为true
//null类型转换为boolean类型是false
//undefined转换为boolean类型是false
var test1 = undefined;
if (test1) {
console.log("test is true")
} else {
console.log("test is false")
}
这里的“+”号表示转换为number类型
输出结果
41
main.js:51 41
main.js:54 flag = 0
main.js:64 test is false
2.5 流程控制语句
//if
var count = 5;
if (count == 5) {
console.log("count = " + count);
}
//switch
var num = 4;
switch (num) {
case 4:
console.log("周四") ;
break;
case 3:
console.log("周三");
break;
default:
console.log("错误");
break;
}
//for
var sum = 10;
for (let i = 3; i<= 20; i++) {
sum += i;
}
console.log("sum = " + sum);
//while
var total = 0;
var i = 0;
while (i <= 30) {
total += i;
i++;
}
console.log("total = " + total);
//dowhile
var sum = 0;
var i = 1;
do {
sum += i;
i++;
}while (i <= 10);
console.log("sum = " + sum);
输出结果
count = 5
main.js:81 周四
main.js:96 sum = 217
main.js:105 total = 465
main.js:114 sum = 55
2.6 函数
//定义方式
function testMethod1(i, j, k) {
console.log("method way 1");
return 1 + j + k;
}
var testMethod2 = function (i, j) {
console.log("method way 2");
return i + j;
}
//函数调用
let result1 = testMethod1(1, 2, 3);
let result2 = testMethod2(1, 2, 3);
console.log("result1 = " + result1);
console.log("result2 = " + result2);
输出结果
method way 1
main.js:124 method way 2
main.js:131 result1 = 6
main.js:132 result2 = 3
3 JavaScript常用对象
3.1 Array对象
var array1 = new Array(1, 2, 3);
var array2 = [1, 2, 3];
console.log("array1 = " + array1);
console.log("array2 = " + array2);
//元素访问
var value = array1[2];
console.log("value = " + value);
//数组可动态拓展
var array3 = [1, 2, 3];
array3[10] = 20;
console.log("array3 = " + array3);
console.log("array3[4] = " + array3[4] );
//可添加不同类型
array3[4] = "value";
console.log("array3[4] = " + array3[4] );
//属性
console.log("array3.length = " + array3.length);
//方法
array3.push(30);
console.log("after push array3 = " + array3);
array3.splice(2, 1);
console.log("after splice array3 = " + array3);
输出结果
array1 = 1,2,3
main.js:140 array2 = 1,2,3
main.js:144 value = 3
main.js:149 array3 = 1,2,3,,,,,,,,20
main.js:150 array3[4] = undefined
main.js:154 array3[4] = value
main.js:157 array3.length = 11
main.js:161 after push array3 = 1,2,3,,value,,,,,,20,30
main.js:164 after splice array3 = 1,2,,value,,,,,,20,30
3.2 String 对象
var str = ' abc ';
console.log( 1 + str + 1);
console.log( 1 + str.trim() + 1);
输出结果
1 abc 1
main.js:170 1abc1
3.3 自定义对象
var person = {
name : "吕布",
age : 24,
fight: function () {
console.log("吕布打架");
}
}
person.fight();
输出结果
吕布打架
4 Bom
Bom:Browser Object Model浏览器对象模型
window: 浏览器窗口对象
navigator: 浏览器对象
screen: 屏幕对象
history: 历史记录对象
Location: 地址栏对象
4.1 Window对象
4.1.1 获取window对象
window对象不需要创建,可以直接使用
显示调用
window.alert("Hello Tom!");
隐式调用
alert("Hello Jerry!");
4.1.2 window对象属性
window.history
window.location
window.navigator
window.screen
4.1.3 window对象函数
1 window.confirm()
var flag = confirm("确认删除?");
alert(flag);
2 window.setInterval()
3s后输出日志
setTimeout(function (){
console.log("Time out");
}, 3000);
每间隔2s输出日志
setInterval(function (){
console.log("interval()")
}, 2000);
4.1.4 案例
<body>
<input type="button" onclick="on()" value="开灯">
<img id="myImage" border="0" src="../img/off.gif" style="text-align:center;">
<input type="button" onclick="off()" value="关灯">
<script>
function on() {
document.getElementById('myImage').src="../img/on.gif";
}
function off() {
document.getElementById('myImage').src="../img/off.gif";
}
</script>
</body>
效果图
4.2 History对象
window.history.back() //跳转到上一个访问的页面
window.history.forward()//跳转到下一个访问的页面
4.3 Location对象
4.3.1 获取location对象
window.location.方法();
location.方法();
4.3.2 Location对象属性
点确定后,会跳转到新网页
alert("将要跳转到百度")
location.href = "http://www.baidu.com"
3s后跳转到百度首页
document.write("2s后跳转到首页")
setTimeout(function () {
location.href = "http://www.baidu.com"
}, 3000);
5 DOM
Dom:Document Object Model 文档对象模型将Html文档的各个组成部分封装为对象
Document: 整个文档对象
Element: 元素对象
Attribute: 属性对象
Text: 文本对象
Comment:注释对象
作用
改变html元素内容
改变html元素格式css
对Html dom事件作出反应
添加和删除html元素
5.1 获取Element对象
<body>
<img id="light" src="../img/off.gif"> <br>
<div class="cls">英雄联盟</div> <br>
<div class="cls">LOL</div> <br>
<input type="checkbox" name = "hoppy"> 吃饭
<input type="checkbox" name = "hoppy"> 睡觉
<input type="checkbox" name = "hoppy"> 遛弯
<br>
<script src="../js/main.js"></script>
</body>
1 获取img元素对象
var img = document.getElementById("light")
console.log(img);
输出
<img id="light" src="../img/off.gif">
2 获取多有的div元素对象
var divs = document.getElementsByTagName("div")
console.log("divs.length = " + divs.length);
for (let i = 0; i < divs.length; i++) {
console.log("div " + i + " = " + divs[i]);
}
输出结果
divs.length = 2
main.js:248 div 0 = [object HTMLDivElement]
main.js:248 div 1 = [object HTMLDivElement]
3 获取所有满足name="hobby"条件的元素对象
var hoppys = document.getElementsByName("hoppy");
for (let i = 0; i < hoppys.length; i++) {
console.log("hoppys " + i + ", = " + hoppys[i]);
}
输出结果
hoppys 0, = [object HTMLInputElement]
hoppys 1, = [object HTMLInputElement]
hoppys 2, = [object HTMLInputElement]
4 获取所有满足class='cls’条件元素对象
输出结果
var clazz = document.getElementsByClassName('cls');
for (let i = 0; i < clazz.length; i++) {
console.log("clazz " + i + " = " + clazz[i]);
}
日志输出
clazz 0 = [object HTMLDivElement]
clazz 1 = [object HTMLDivElement]
5.2 Element对象使用
// 1 点亮灯泡
var img = document.getElementById("light");
img.src = "../img/on.gif";
//2 将所有的div标签的内容替换为 "打游戏"
var divs = document.getElementsByTagName("div");
for (let i = 0; i < divs.length; i++) {
divs[i].innerHTML = "打游戏";
}
//3 将所有的复选框改为被选中状态
var hobbys = document.getElementsByName("hoppy");
for (let i = 0; i < hobbys.length; i++) {
hobbys[i].checked = true;
}
修改前效果
修改后效果
6 事件监听
6.1 事件绑定
<input type="button" value="点我" onclick="on()"><br>
<script>
function on() {
console.log("button has been clicked");
}
</script>
6.2 事件类型
onclick 点击事件
onblur 元素失去焦点
onfocus 元素获取焦点
onload 某个页面或图像被完全加载
onsubmit 表单提交时触发该事件
onmouseover 元素被转移到某元素之上
onmouseout 鼠标从某元素移开
7 表单验证案例
<body>
<div class="form-div">
<div class="reg-content">
<h2>欢迎注册</h2>
<span>已有账号</span> <a href="#">登录</a>
</div>
<form id="reg-form" action="#" method="get">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username"><br>
<span id="username_err" class="err_msg" style="display:none">用户名非法</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password"><br>
<span id="password_err" class="err_msg" style="display: none">密码格式错误</span>
</td>
</tr>
<tr>
<td>手机号</td>
<td class="inputs">
<input name="tel" type="text" id="tel"><br>
<span id="tel_err" class = "err_msg" style = "display:none">手机号格式有误</span>
</td>
</tr>
</table>
<div class="buttons">
<input value="注册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
/*用户名校验*/
var usernameInput = document.getElementById("username");
usernameInput.onblur = checkUsername;
function checkUsername() {
var username = usernameInput.value.trim();
var fit = username.length >= 6 && username.length <= 12;
if (fit) {
document.getElementById("username_err").style.display = "none";
} else {
document.getElementById("username_err").style.display = '';
}
console.log("checkUsername fit = " + fit);
return fit;
}
/*密码校验*/
let passwordInput = document.getElementById("password");
passwordInput.onblur = checkPwd;
function checkPwd() {
let password = passwordInput.value.trim();
let fit = password.length >= 6 && password.length <= 12;
console.log(password.length >= 6)
if (fit) {
document.getElementById("password_err").style.display = 'none';
} else {
document.getElementById("password_err").style.display = '';
}
console.log("checkPwd fit = " + fit);
return fit;
}
/*手机号校验*/
let telInput = document.getElementById("tel");
telInput.onblur = checkPhone;
function checkPhone() {
let tel = telInput.value.trim();
let fit = tel.length === 11;
if (fit) {
document.getElementById("tel_err").style.display = 'none';
} else {
document.getElementById("tel_err").style.display = '';
}
console.log("checkPhone fit = " + fit);
return fit;
}
/*表单校验*/
let regForm = document.getElementById("reg-form");
regForm.onsubmit = function () {
let flag = checkUsername() && checkPhone() && checkPwd();
return flag;
}
</script>
</body>
8 RegExp对象
<script>
//1 匹配单词或者数字,位数: 6~12
let regName = /^\w{6,12}$/
let str1 = "adcab";
let str2 = "adcaba";
let flag1 = regName.test(str1)
let flag2 = regName.test(str2)
console.log("flag1 = " + flag1 + ", flag2 = " + flag2);
//2 匹配手机号
var regPhone = /^[1]\d{10}$/
let phoneNum1 = 13115158971;
let phoneNum2 = 1311515891;
let fitPhone1 = regPhone.test(phoneNum1);
let fitPhone2 = regPhone.test(phoneNum2);
console.log("fitPhone1 = " + fitPhone1 + ", fitPhone2 = " + fitPhone2);
</script>
结果输出
flag1 = false, flag2 = true
fitPhone1 = true, fitPhone2 = false