一、DOM对象
1.什么是HTML DOM
HTML Document Object Model(文档对象模型---标签)
2.功能:定义了访问(查找)和操作HTML文档的标准方法
3.HTML DOM 把 HTML 文档呈现为带有元素、属性和文本的树结构(节点树)
DOM树的目的:导航标签
4.DOM节点
1.DOM树的每一个节点对象(Node)就是每一个标签
2.节点主要有两个: 1. document (整个结构html标签) 2. element (里面的每一个标签)
3.节点关系:
节点树中的节点彼此拥有层级关系。
父(parent),子(child)和同胞(sibling)等术语用于描述这些关系。父节点拥有子节点。同级的子节点被称为同胞(兄弟或姐妹)。
在节点树中,顶端节点被称为根(root)
每个节点都有父节点、除了根(它没有父节点)
一个节点可拥有任意数量的子
同胞是拥有相同父节点的节点
4.节点查找
1.直接查找
document.getElementById(“idname”) #得到标签对象
document.getElementsByTagName(“tagname”) #得到数组对象
document.getElementsByName(“name”) #得到数组对象
document.getElementsByClassName(“name”) #得到数组对象
<script> var div1=document.getElementById("div1"); ////支持; // var ele= div1.getElementsByTagName("p"); // alert(ele.length); ////支持 // var ele2=div1.getElementsByClassName("div2"); // alert(ele2.length); ////不支持 // var ele3=div1.getElementById("div3"); // alert(ele3.length); ////不支持 // var ele4=div1.getElementsByName("yuan"); // alert(ele4.length) </script>
注意:设计到寻找元素,注意<script>标签的位置!
注意:每一个标签都是一个对象,对象就可以调用属性和方法
2.导航查找 :通过某个标签定位到某些标签
导航节点属性:
'''
parentElement // 父节点标签元素
children // 所有子标签
firstElementChild // 第一个子标签元素
lastElementChild // 最后一个子标签元素
nextElementtSibling // 下一个兄弟标签元素
previousElementSibling // 上一个兄弟标签元素
'''
注意,js中没有办法找到所有的兄弟标签!
5.节点属性操作
1、属性操作
var ele=document.getElementsByClassName("c1")[0];
(1) 文本操作:
ele.innerText 取值
ele.innerText="Egon"; 赋值
ele.innerHTML; 取值
ele.innerHTML="<a href=''>click</a>"; 赋值
区别在 innerHTML可以取值和赋值标签,而innerText不行
(2)属性操作
// 取属性值(对所有的属性都可以,除了class类)
console.log(ele.getAttribute("id"));
console.log(ele.id); --简便
// 属性赋值:(对所有的属性都可以,除了class类)
ele.setAttribute("id","d2")
ele.id="d2"; --简便
// class属性
console.log(ele.className); 查看
ele.classList.add("hide"); 增加
ele.classList.remove("hide"); 删除
2 、节点操作(增删改)
1 创建节点 : document.createElement("标签名")
2 添加节点 : ele_parent.appentChild(ele_child)
3 删除节点 : ele_parent.removeChild(ele_child)
4 替换节点 : ele_parent.repalceChild(newnode, 某个节点)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .c1 { 8 500px; 9 height: 300px; 10 border: 1px solid red; 11 } 12 </style> 13 14 <script> 15 window.onload = function () { //监听 加载完成之后执行 16 var ele = document.getElementsByClassName("addBtn")[0]; 17 var ele_del = document.getElementsByClassName("delBtn")[0]; 18 var eleBtn = document.getElementsByClassName("repalceBtn")[0]; 19 20 21 // 绑定的添加节点事件 22 ele.onclick = function () { 23 // 创建一个a标签 24 var ele_a = document.createElement("a"); 25 console.log(ele_a); // <a></a> 26 ele_a.innerHTML = "点击"; // <a>点击</a> 27 ele_a.setAttribute("href", "http://www.baidu.com"); 28 ele_a.id = "d1"; 29 30 // 创建img标签 31 32 var ele_img = document.createElement("img"); // <img> 33 ele_img.src = "Bootstrap_i2.png"; // <img src=""> 34 ele_img.height = 50; 35 ele_img.width = 50; 36 37 // 添加标签 38 39 // 找到父标签 40 ele_p = document.getElementsByClassName("c1")[0]; 41 ele_p.appendChild(ele_a) 42 // ele_p.appendChild(ele_img) 43 44 }; 45 // 绑定删除节点事件 46 ele_del.onclick = function () { 47 var ele_p = document.getElementById("p1"); 48 var ele_parent = document.getElementsByClassName("c1")[0]; 49 50 ele_parent.removeChild(ele_p); 51 52 }; 53 // 绑定替换节点事件 54 eleBtn.onclick = function () { 55 //创建的 新节点 56 var ele_img = document.createElement("img"); // <img> 57 ele_img.src = "Bootstrap_i2.png"; // <img src=""> 58 ele_img.height = 50; 59 ele_img.width = 50; 60 61 // 被替换的节点 62 var ele_p = document.getElementById("p1"); 63 64 // 父节点 65 66 var ele_parent = document.getElementsByClassName("c1")[0] 67 68 // 做替换 69 70 ele_parent.replaceChild(ele_img, ele_p) 71 } 72 }; 73 74 </script> 75 76 77 </head> 78 <body> 79 80 <div class="c1"> 81 <p id="p1">p1</p> 82 </div> 83 <button class="addBtn">ADD</button> 84 <button class="delBtn">del</button> 85 <button class="repalceBtn">repalceBtn</button> 86 87 </body> 88 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script> 7 window.onload = function () { 8 9 // 表格操作 10 11 var eles = document.getElementsByClassName("del"); 12 for (var i = 0; i < eles.length; i++) { 13 eles[i].onclick = function () { 14 // console.log(this.parentElement.parentElement); 15 var ele_tr = this.parentElement.parentElement; 16 17 var ele_tbody = document.getElementById("t1"); 18 19 ele_tbody.removeChild(ele_tr); 20 21 } 22 } 23 24 }; 25 26 </script> 27 28 29 </head> 30 <body> 31 32 <table border="1"> 33 34 <tbody id="t1"> 35 <tr> 36 <td><input type="checkbox"></td> 37 <td><input type="text"></td> 38 <td> 39 <button class="del">del1</button> 40 </td> 41 </tr> 42 43 <tr> 44 <td><input type="checkbox"></td> 45 <td><input type="text"></td> 46 <td> 47 <button class="del">del2</button> 48 </td> 49 </tr> 50 51 <tr> 52 <td><input type="checkbox"></td> 53 <td><input type="text"></td> 54 <td> 55 <button class="del">del3</button> 56 </td> 57 </tr> 58 59 <tr> 60 <td><input type="checkbox"></td> 61 <td><input type="text"></td> 62 <td> 63 <button class="del">del3</button> 64 </td> 65 </tr> 66 67 </tbody> 68 69 </table> 70 71 72 </body> 73 </html>
5.事件
<body>
<!--事件绑定方式1-->
<div onclick="foo(this)">DIV</div>
<div class="c1">DIV2</div>
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
<li>444</li>
</ul>
<script>
// <!--事件绑定方式1-->
function foo(self) {
console.log(self);
// var ele=document.getElementsByTagName("div")[0];
self.style.color="red";
}
// 事件绑定方式2: 标签对象.on事件=function(){}
var ele=document.getElementsByClassName("c1")[0];
ele.onclick=function () {
console.log(this); // this 代指: 当前触发事件的标签对象;
this.style.fontSize="30px"
};
// ul li 事件
var eles_li=document.getElementsByTagName("li");
for (var i=0;i<eles_li.length;i++){
eles_li[i].onclick=function () {
console.log(this.innerText);
//console.log(i); // i 为什么是4?
//console.log(eles_li[i].innerText);
}
}
</script>
</body>
练习:左侧菜单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>左侧菜单实例</title> <style> .left{ 30%; height: 600px; background-color: sandybrown; float: left; } .right{ 70%; height: 600px; background-color: deepskyblue; float: left; } .item { /*下面的div不上来,因为给item设置了边框 100%; height: 200px; /*border: 1px solid red;*/ } .title{ 100%; height: 25px; background-color: steelblue; } .hide{ display: none; } </style> </head> <body> <div class="left"> <div class="item"> <div class="title">菜单一</div> <div class="con hide"> <ul> <li>第一章</li> <li>第二章</li> <li>第三章</li> <li>第四章</li> </ul> </div> </div> <div class="item"> <div class="title">菜单二</div> <div class="con hide"> <ul> <li>第一章</li> <li>第二章</li> <li>第三章</li> <li>第四章</li> </ul> </div> </div> <div class="item"> <div class="title">菜单三</div> <div class="con hide"> <ul> <li>第一章</li> <li>第二章</li> <li>第三章</li> <li>第四章</li> </ul> </div> </div> </div> <div class="right"></div> <script> // 先找到要增加鼠标点击事件的标签 var ele_title= document.getElementsByClassName('title'); for(var i =0;i<ele_title.length;i++){ ele_title[i].onclick = function () { // 显示点击标签下的兄弟标签 // 先找到当前的标签title // console.log(this); //this就代表当前点击的标签 // console.log(this.nextElementSibling) ;//下一个兄弟标签 <div class="con hide">,然后把hide去了 // 再找到title下的兄弟标签 this.nextElementSibling.classList.remove('hide'); //隐藏另外两个con标签 for (j = 0;j<ele_title.length;j++){ console.log(j); if(ele_title[j]!=this){ ele_title[j].nextElementSibling.classList.add('hide'); } } } } </script> </body> </html>
1、onload 事件:
onload 属性开发中 只给 body元素加.这个属性的触发 标志着 页面内容被加载完成.应用场景: 当有些事情我们希望页面加载完立刻执行,那么可以使用该事件属性.
2、onsubmit 事件:
当表单在提交时触发. 该属性也只能给form元素使用.应用场景: 在表单提交前验证用户输入是否正确.如果验证失败.在该方法中我们应该阻止表单的提交.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" id="submit">
<p>姓名<input type="text" name="user" id="user"></p>
<p>年龄<input type="text" name="age" id="age"></p>
<input type="submit" > 默认自带一个提交事件
</form>
<script>
var ele_form=document.getElementById("submit");
var ele_user=document.getElementById("user");
var ele_age=document.getElementById("age");
ele_form.onsubmit=function (event) { //给form表单添加onsubmit事件就相当于给input-submit标签添加
var username=ele_user.value;
var age=ele_age.value;
alert(username);
alert(age);
// 两种阻止默认事件发生的方式
// 方式1
return false
// 方式2
// event.preventDefault()
}
</script>
</body>
</html>
Event 对象:Event 对象代表事件的状态,比如事件在其中发生的元素、键盘按键的状态、鼠标的位置、鼠标按钮的状态。
事件通常与函数结合使用,函数不会在事件发生前被执行!event对象在事件发生时系统已经创建好了,并且会在事件函数被调用时传给事件函数.我们获得仅仅需要接收一下即可.比如onkeydown,我们想知道哪个键被按下了 ,需要问下event对象的属性,这里就是KeyCode.
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6 </head>
7 <body>
8
9 <input type="text" id="test">
10
11 <script>
12 var ele=document.getElementById("test")
13 ele.onkeydown=function (e) {
14 console.log(e.keyCode);
15
16 if (e.keyCode==13){
17 alert(666)
18 }
19 }
20 </script>
21 </body>
22 </html>
4、事件传播
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>Title</title>
6
7 <style>
8 .c1{
9 200px;
10 height: 200px;
11 background-color: wheat;
12 }
13
14 .c2{
15 100px;
16 height: 100px;
17 background-color: royalblue;
18 }
19 </style>
20 </head>
21 <body>
22 <div class="c1">
23 <div class="c2"></div>
24 </div>
25
26 <script>
27 var ele1=document.getElementsByClassName("c1")[0];
28 var ele2=document.getElementsByClassName("c2")[0];
29
30 ele1.onclick=function () {
31 alert(123)
32 };
33
34 ele2.onclick=function (event) {
35 alert(456);
36 event.stopPropagation() // 阻止事件传播
37 }
38 </script>
39 </body>
40 </html>
5、onblur与onfocus事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" value="username" id="search">
<script>
var ele=document.getElementById("search")
ele.onfocus=function () {
this.value=""
};
ele.onblur=function () {
if(this.value.trim()==""){
this.value="username"
}
}
</script>
</body>
</html>
6、模态对话框练习
<!DOCTYPE html>
<html>
<!--bug : 1 添加的行不能用删除按钮, 2 输入为空时会添加行-->
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css"/>
<style>
.container {
margin-top: 80px;
}
.row {
margin-top: 10px;
}
.c1 {
margin-left: 12px;
margin-right: 15px;
margin-top: -10px;
}
.c2 {
margin-left: 15px;
margin-right: 15px;
}
/*.c3 {*/
/*margin-left: 100px;*/
/*}*/
.c4 {
margin-left: 50px;
}
.c5 {
margin-top: -30px;
}
.c3 {
280px;
height: 30px;
}
.c8 {
margin-right: 50px;
}
.add {
display: block;
float: right;
height: 36px;
72px;
background-color: dodgerblue;
color: white;
border-radius: 5px;
}
.back {
100%;
height: 2000px;
border: 1px solid red;
}
.shade {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: darkgray;
opacity: 0.5;
}
.model {
position: fixed;
top: 100px;
left: 40%;
300px;
height: 200px;
background-color: white;
}
.hide {
display: none;
}
#i8 {
margin-left: 61px;
}
.i9 {
margin-left: 20px;
}
#i6 {
margin-top: 10px;
}
#btn {
background-color: dodgerblue;
color: white;
margin-left: 170px;
border-radius: 3px;
height: 28px;
65px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">Panel heading</div>
<div class="panel-body">
</div>
<div class="row c1">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="搜索">
</div>
<button type="submit" class="btn btn-primary">搜索</button>
<input type="button" value="添加" class="add" id="ss"/>
<!--<button type="submit" class="pull-right" id="ss">添加</button>-->
</form>
</div>
<div class="row c2">
<table class="table table-striped table-bordered table-hover table-condensed">
<tbody id="i1">
<tr>
<th>#</th>
<th>Column heading</th>
<th>Column heading</th>
<th>Column heading</th>
<th>Column heading</th>
</tr>
<tr>
<th>1</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>2</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>3</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>4</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>5</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>6</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>7</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>8</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
<tr>
<th>9</th>
<td>Column heading</td>
<td>Column heading</td>
<td>Column heading</td>
<td class="c3">
<button type="submit" class="btn btn-success c4">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"> 编辑</span>
</button>
<button type="submit" class="btn btn-danger pull-right c8">
<span class="glyphicon glyphicon-remove" aria-hidden="true"> 删除</span>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="row c2">
<nav aria-label="Page navigation " class="pull-right c5">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div class="shade hide"></div>
<div class="model hide">
<form action="" id="i6">
<p id="i8">id <input type="text" id="i60"></p>
<p class="i9">Column <input type="text" id="i61"></p>
<p class="i9">Column <input type="text" id="i62"></p>
<p class="i9">Column <input type="text" id="i63"></p>
<input type="button" id="btn" value="提交">
</form>
</div>
<script>
var eles = document.getElementsByClassName("c8");
for (var i = 0; i < eles.length; i++) {
eles[i].onclick = function () {
var ele_tr = this.parentElement.parentElement;
var ele_tbody = this.parentElement.parentElement.parentElement;
ele_tbody.removeChild(ele_tr);
}
}
</script>
<script>
var ele_adda = document.getElementById("ss");
var ele_mdoel = document.getElementsByClassName("model")[0];
var ele_shade = document.getElementsByClassName("shade")[0];
ele_adda.onclick = function () {
ele_mdoel.classList.remove("hide");
ele_shade.classList.remove("hide")
}
var ele_sub = document.getElementById('btn');
ele_sub.onclick = function () {
ele_mdoel.classList.add("hide");
ele_shade.classList.add("hide")
var ele_a = document.createElement("tr");
var ele_1 = document.getElementById('i60');
var ele_2 = document.getElementById('i61');
var ele_3 = document.getElementById('i62');
var ele_4 = document.getElementById('i63');
var elee_1 = document.createElement("th");
elee_1.innerText = ele_1.value
ele_a.appendChild(elee_1)
var elee_2 = document.createElement("td");
elee_2.innerText = ele_2.value
ele_a.appendChild(elee_2)
var elee_3 = document.createElement("td");
elee_3.innerText = ele_3.value
ele_a.appendChild(elee_3)
var elee_4 = document.createElement("td");
elee_4.innerText = ele_4.value
ele_a.appendChild(elee_4)
var elee_5 = document.createElement("td");
elee_5.classList.add('c3');
var elee_6 = document.createElement("button");
elee_6.type = 'submit';
elee_6.classList.add('btn');
elee_6.classList.add('btn-success');
elee_6.classList.add('c4');
var elee_8 = document.createElement("span");
elee_8.classList.add('glyphicon');
elee_8.classList.add('glyphicon-pencil');
elee_8.innerHTML = ' 编辑'
elee_6.appendChild(elee_8);
elee_5.appendChild(elee_6);
var elee_7 = document.createElement("button");
elee_7.type = 'submit';
elee_7.classList.add('btn')
elee_7.classList.add('btn-danger')
elee_7.classList.add('pull-right')
elee_7.classList.add('c8')
var elee_9 = document.createElement("span");
elee_9.classList.add('glyphicon');
elee_9.classList.add('glyphicon-remove');
elee_9.innerHTML = ' 删除';
elee_7.appendChild(elee_9);
elee_5.appendChild(elee_7);
ele_a.appendChild(elee_5)
var ele_tr = document.getElementById('i1');
ele_tr.appendChild(ele_a);
}
</script>
</body>
</html>
7、正反选实例练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button class="selectAll">全选</button>
<button class="reverse">反选</button>
<button class="cancel">取消</button>
<hr>
<table border="1">
<tr>
<td><input type="checkbox" class="check"></td>
<td>111</td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>111</td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>111</td>
<td>111</td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>111</td>
<td>111</td>
</tr>
</table>
<script>
// 方式1
var ele_selectAll=document.getElementsByClassName("selectAll")[0];
var ele_reverse=document.getElementsByClassName("reverse")[0];
var ele_cancel=document.getElementsByClassName("cancel")[0];
var ele_input=document.getElementsByClassName("check");
ele_selectAll.onclick=function () {
for(var i=0;i<ele_input.length;i++){
ele_input[i].checked="checked"
}
};
ele_cancel.onclick=function () {
for(var i=0;i<ele_input.length;i++){
ele_input[i].checked=""
}
};
ele_reverse.onclick=function () {
for(var i=0;i<ele_input.length;i++){
var ele=ele_input[i];
if(ele.checked){
ele.checked=""
}
else {
ele.checked="checked"
}
}
};
// 方式2
var eles_button=document.getElementsByTagName("button");
var ele_input=document.getElementsByClassName("check");
for (var i=0;i<eles_button.length;i++){
eles_button[i].onclick=function () {
if(this.innerHTML=="全选"){
for(var i=0;i<ele_input.length;i++){
ele_input[i].checked="checked"
}
}
else if (this.innerHTML=="取消"){
....
}
else {
....
}
}
}
</script>
</body>
</html>
8、onchange 事件
域的内容被改变。 应用场景:通常用于表单元素,当元素内容被改变时触发.(三级联动)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="">
<select name="pro" id="s1">
<option value="0">请输入省份</option>
<option value="hebei">河北省</option>
<option value="henan">河南省</option>
<option value="beijing">北京省</option>
</select>
<select name="city" id="c1">
<option value="0">请输入城市</option>
</select>
</form>
<script>
var data={"hebei":["保定","石家庄"],"henan":["郑州","开封"],"beijing":["朝阳","昌平"]};
var select_province=document.getElementById("s1");
var select_city=document.getElementById("c1");
select_province.onchange=function () {
// console.log(this.value);
var province=this.value;
var citys=data[province];
// console.log(citys);
// 清空操作
// console.log(select_city.options);
select_city.children.length=1; //保留一个
// select_city.children.length=0; //全部清空
// select_city.options.length=0; //等同上一个,全部清空
for(var i=0;i<citys.length;i++){
var ele_option=document.createElement("option"); // <option></option>
ele_option.innerHTML=citys[i]; // <option>郑州</option>
ele_option.value=i+1; // <option value=1>郑州</option>
select_city.appendChild(ele_option)
}
}
</script>
</body>
</html>
9、onmouseleave 与onmouseout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.title{
background-color: goldenrod;
line-height: 30px;
}
.item{
line-height: 20px;
background-color: #cccccc;
}
.hide{
display: none;
}
</style>
</head>
<body>
<div class="box">
<div class="title">onmouseover</div>
<div class="con hide">
<div class="item"><a href="">111</a></div>
<div class="item"><a href="">222</a></div>
<div class="item"><a href="">333</a></div>
</div>
</div>
<script>
var ele_title=document.getElementsByClassName("title")[0];
var ele_box=document.getElementsByClassName("box")[0];
ele_title.onmouseover=function () {
this.nextElementSibling.classList.remove("hide")
};
ele_box.onmouseleave=function () {
ele_title.nextElementSibling.classList.add("hide")
}
// onmouseout 1.不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。
// onmouseleave 2.只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。
</script>
</body>
</html>
10、onselect 事件 , 文本被选中。
11、事件委派
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
<li>111</li>
<li>222</li>
<li>333</li>
</ul>
<button>Add</button>
<script>
var eles_li=document.getElementsByTagName("li");
var ele_btn=document.getElementsByTagName("button")[0];
var ele_ul=document.getElementsByTagName("ul")[0];
// 添加li
ele_btn.onclick=function () {
var ele_li=document.createElement("li");
ele_li.innerHTML=444;
ele_ul.appendChild(ele_li)
};
// 这种方式做出来的效果-- 新添加的标签不会alert文本
// 绑定事件
// for(var i=0;i<eles_li.length;i++){
// eles_li[i].onclick=function () {
// alert(this.innerHTML)
// }
// }
//解决方法
// 事件委派 --从变化的标签开始往上找,直到找到不变化的标签,当作绑定事件(addEventListener)的标签(ele_ul)
ele_ul.addEventListener("click",function (e) {
console.log(e.target); // 标签
console.log(e.target.tagName); // 标签名称
if(e.target.tagName=="LI"){ //筛选想操作的标签
console.log("OK")
}
})
</script>
</body>
</html>
12、ondblclick 事件 当用户双击某个对象时调用的事件句柄。
13、
onkeydown 某个键盘按键被按下。 应用场景: 当用户在最后一个输入框按下回车按键时,表单提交.
onkeypress 某个键盘按键被按下并松开。
onkeyup 某个键盘按键被松开。
14、
onmousedown 鼠标按钮被按下。
onmousemove 鼠标被移动。
onmouseout 鼠标从某元素移开。
onmouseover 鼠标移到某元素之上。
onmouseleave 鼠标从元素离开
二、实例练习
1 左侧菜单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; } .left{ 20%; height: 500px; float: left; background-color: wheat; } .right{ float: left; 80%; height: 500px; background-color: lightgray; } .title{ text-align: center; line-height: 40px; background-color: #0e90d2; color: white; } .item{ padding: 10px; } .hide{ display: none; } </style> </head> <body> <div class="outer"> <div class="left"> <div class="item"> <div class="title">菜单一</div> <ul class="con"> <li>111</li> <li>111</li> <li>111</li> </ul> </div> <div class="item"> <div class="title">菜单二</div> <ul class="con hide"> <li>222</li> <li>222</li> <li>222</li> </ul> </div> <div class="item"> <div class="title">菜单三</div> <ul class="con hide"> <li>333</li> <li>333</li> <li>333</li> </ul> </div> </div> <div class="right"></div> </div> <script> var eles_title=document.getElementsByClassName("title"); for (var i=0;i<eles_title.length;i++){ eles_title[i].onclick=function(){ this.nextElementSibling.classList.remove("hide"); for(var j=0;j<eles_title.length;j++){ if (eles_title[j]!=this){ eles_title[j].nextElementSibling.classList.add("hide") } } } } </script> </body> </html>
2 搜索框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function Focus(){ var input=document.getElementById("ID1"); if (input.value=="请输入用户名"){ input.value=""; } } function Blurs(){ var ele=document.getElementById("ID1"); var val=ele.value; if(!val.trim()){ ele.value="请输入用户名"; } } </script> </head> <body> <input id="ID1" type="text" value="请输入用户名" onblur="Blurs()" onfocus="Focus()"> </body> </html>
3 模态对话框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .back{ background-color: white; height: 2000px; } .shade{ position: fixed; top: 0; bottom: 0; left:0; right: 0; background-color: grey; opacity: 0.4; } .hide{ display: none; } .models{ position: fixed; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; height: 200px; 200px; background-color: wheat; } </style> </head> <body> <div class="back"> <input class="c" type="button" value="click"> </div> <div class="shade hide handles"></div> <div class="models hide handles"> <input class="c" type="button" value="cancel"> </div> <script> var eles=document.getElementsByClassName("c"); var handles=document.getElementsByClassName("handles"); for(var i=0;i<eles.length;i++){ eles[i].onclick=function(){ if(this.value=="click"){ for(var j=0;j<handles.length;j++){ handles[j].classList.remove("hide"); } } else { for(var j=0;j<handles.length;j++){ handles[j].classList.add("hide"); } } } } </script> </body> </html>
4 表格案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button class="select_all">全选</button> <button class="select_reverse">反选</button> <button class="cancel">取消</button> <hr> <table class="server_table" border="2px" cellspacing="2px"> <tr> <td><input type="checkbox" class="item"></td> <td>111</td> <td>111</td> <td>111</td> </tr> <tr> <td><input type="checkbox" class="item"></td> <td>222</td> <td>222</td> <td>222</td> </tr> <tr> <td><input type="checkbox" class="item"></td> <td>333</td> <td>333</td> <td>333</td> </tr> <tr> <td><input type="checkbox" class="item"></td> <td>444</td> <td>444</td> <td>444</td> </tr> </table> <script> /* var ele_all=document.getElementsByClassName("select_all")[0]; var ele_reverse=document.getElementsByClassName("select_reverse")[0]; var ele_cancel=document.getElementsByClassName("cancel")[0]; var input_arr=document.getElementsByClassName("item"); ele_all.onclick=function(){ for(var i=0;i<input_arr.length;i++){ console.log(input_arr[i]); var input=input_arr[i]; input.checked=true; } }; ele_cancel.onclick=function(){ for(var i=0;i<input_arr.length;i++){ console.log(input_arr[i]); var input=input_arr[i]; input.checked=false; } }; ele_reverse.onclick=function(){ for(var i=0;i<input_arr.length;i++){ console.log(input_arr[i]); var input=input_arr[i]; if(input.checked){ input.checked=false; } else{ input.checked=true; } } }; */ var input_arr=document.getElementsByClassName("item"); var button_arr=document.getElementsByTagName("button"); for(var i=0;i<button_arr.length;i++){ button_arr[i].onclick=function(){ for (var j=0;j<input_arr.length;j++){ var inp=input_arr[j] if(this.innerText=="全选"){ console.log("ok"); inp.checked=true; } else if(this.innerText=="取消"){ inp.checked=false; } else { if(inp.checked){ inp.checked=false; }else { inp.checked=true; } } } } } </script> </body> </html>
5 select移动
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .outer{ margin: 0 auto; background-color: darkgray; 80%; height: 600px;margin-top: 30px; word-spacing: -5px; } #left{ display: inline-block; 100px ; height: 140px; background-color: wheat; text-align: center; } #choice{ display: inline-block; height: 140px; background-color: darkolivegreen; vertical-align: top; padding:0 5px; } #choice button{ margin-top: 20px; } #right{ display: inline-block; 100px ; height: 140px; background-color: wheat; text-align: center; line-height: 140px; } </style> </head> <body> <div class="outer"> <select multiple="multiple" size="5" id="left"> <option>红楼梦</option> <option>西游记</option> <option>水浒传</option> <option>JinPingMei</option> <option>三国演义</option> </select> <span id="choice"> <button id="choose_move"> > </button><br> <button id="all_move"> >> </button> </span> <select multiple="multiple" size="10" id="right"> <option>放风筝的人</option> </select> </div> <script> var choose_move=document.getElementById("choose_move"); var all_move=document.getElementById("all_move"); var right=document.getElementById("right"); var left=document.getElementById("left"); var options=left.options; choose_move.onclick=function(){ for (var i=0; i<options.length;i++){ var option=options[i]; if(option.selected==true){ // var news=option.cloneNode(true); // console.log(news); right.appendChild(option); i--; } } }; all_move.onclick=function(){ for (var i=0; i<options.length;i++){ var option=options[i]; right.appendChild(option); i--; }; }; /* var buttons=document.getElementsByTagName("button"); for(var i=0;i<buttons.length;i++) { buttons[i].onclick = function () { for (var i = 0; i < options.length; i++) { var option = options[i]; if (this.innerText == ">") { if (option.selected == true) { // var news=option.cloneNode(true); // console.log(news); right.appendChild(option); i--; } } else { right.appendChild(option); i--; } } }; } */ </script> </body> </html>
6 二级联动
<select id="province"> <option>请选择省:</option> </select> <select id="city"> <option>请选择市:</option> </select> <script> data={"河北省":["廊坊","邯郸"],"北京":["朝阳区","海淀区"]}; var p=document.getElementById("province"); var c=document.getElementById("city"); for(var i in data){ var option_pro=document.createElement("option"); option_pro.innerHTML=i; p.appendChild(option_pro); } p.onchange=function(){ pro=(this.options[this.selectedIndex]).innerHTML; citys=data[pro]; c.options.length=0; for (var i in citys){ var option_city=document.createElement("option"); option_city.innerHTML=citys[i]; c.appendChild(option_city); } } </script>
7 跑马灯与tab切换
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>tab</title> <style> *{margin:0; padding:0; list-style:none;} body{ font-family: "Helvetica Neue", "Hiragino Sans GB", "Microsoft YaHei", "9ED14F53", Arial, sans-serif; } h3{ text-align: center; color:darkcyan; margin-top: 30px; letter-spacing: 5px; } .box{ 1000px; margin:50px auto 0px; } #title{ line-height: 40px; background-color: rgb(247,247,247); font-size: 16px; font-weight: bold; color: rgb(102,102,102); } #title span{ float: left; 166px; text-align: center; } #title span:hover{ /*color: black;*/ cursor: pointer; } #content{ margin-top: 20px; } #content li{ 1050px; display: none; background-color: rgb(247,247,247); } #content li div{ 156px; margin-right: 14px; float: left; text-align: center; } #content li div a{ font-size: 14px; color: black; line-height: 14px; /* float: left;*/ display: inline-block; margin-top: 10px; } #content li a:hover{ color: #B70606; } #content li div span{ font-size: 16px; line-height: 16px; /*float: left;*/ display: block; color: rgb(102,102,102); margin-top: 10px; } #content img{ float: left; 155px; height: 250px; } #title .select{ background-color: #2459a2; color: white; border-radius: 10%; } #content .show{ display: block; } .show span{ color: red!important; font-size: 30px; } </style> </head> <body> <h3 id="wel">京东商城欢迎您</h3> <!-- direction="right up down left" --> <!-- behavior:滚动方式(包括3个值:scroll、slide、alternate) --> <!-- 说明:scroll:循环滚动,默认效果;slide:只滚动一次就停止;alternate:来回交替进行滚动。 --> <!-- scrollamount="5" 滚动速度 --> <marquee behavior="scroll" direction="right">欢迎您苑昊先生</marquee> <script> function test(){ var mywel = document.getElementById("wel"); var content = mywel.innerText; var f_content = content.charAt(0); var l_content = content.substring(1,content.length); var new_content = l_content + f_content; mywel.innerText = new_content; } // setInterval("test();", 500); </script> <div class="box"> <p id="title"> <span class="select">家用电器</span> <span>家具</span> <span>汽车</span> <span>食品</span> <span>女鞋</span> <span>医疗保健</span> </p> <ul id="content"> <li class="show"> <div><img src="https://img10.360buyimg.com/n1/s450x450_jfs/t4786/325/2470647304/119102/9e1a4ed5/59005841Nd786a8df.jpg" alt="冰箱"><a href="#">容声(Ronshen)冰箱</a><span>价格:5600</span></div> <div><img src="https://img12.360buyimg.com/n1/s450x450_jfs/t3037/347/1290968859/201366/7c1028a0/57c00194N9d0a54c6.jpg" alt="洗衣机"><a href="#">海尔洗衣机</a><span>价格:5400</span></div> <div><img src="https://img11.360buyimg.com/n1/jfs/t3289/128/2393835119/236360/af1d283b/57e0f300N53dde603.jpg" alt="电饭煲"><a href="#">福库(CUCKOO)电饭煲</a><span>价格:3999</span></div> <div><img src="https://img13.360buyimg.com/n1/jfs/t3235/137/2361713777/152258/a6908440/57e098c2N44a90a5d.jpg" alt="智能电视"><a href="#">三星智能电视</a><span>价格:8999</span></div> <div><img src="https://img10.360buyimg.com/n1/jfs/t2053/101/1391591157/215066/572e131b/5696ee9bN2376492d.jpg" alt="净水器"><a href="#">净水器</a><span>价格:1300</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t3175/78/2357430273/262835/9a8e7f65/57e0a3e9Nbda39dd2.jpg" alt="空气净化器"><a href="#">空气净化器</a><span>价格:5300</span></div> </li> <li> <div><img src="https://img12.360buyimg.com/n1/jfs/t1948/172/2877517581/556924/682eb107/56f63dc8Naddf77e5.jpg" alt="沙发"><a href="#">沙发</a><span>价格:2900</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t1948/172/2877517581/556924/682eb107/56f63dc8Naddf77e5.jpg" alt="沙发"><a href="#">沙发</a><span>价格:2900</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t1948/172/2877517581/556924/682eb107/56f63dc8Naddf77e5.jpg" alt="沙发"><a href="#">沙发</a><span>价格:2900</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t1948/172/2877517581/556924/682eb107/56f63dc8Naddf77e5.jpg" alt="沙发"><a href="#">沙发</a><span>价格:2900</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t1948/172/2877517581/556924/682eb107/56f63dc8Naddf77e5.jpg" alt="沙发"><a href="#">沙发</a><span>价格:2900</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t1948/172/2877517581/556924/682eb107/56f63dc8Naddf77e5.jpg" alt="沙发"><a href="#">沙发</a><span>价格:2900</span></div> </li> <li> <div><img src="http://img11.360buyimg.com/n1/jfs/t4969/76/45396935/144539/347153d4/58d9cff4N36872ad6.jpg" alt="长安汽车"><a href="#">长安汽车</a><span>价格:12900</span></div> <div><img src="http://img11.360buyimg.com/n1/jfs/t4969/76/45396935/144539/347153d4/58d9cff4N36872ad6.jpg" alt="长安汽车"><a href="#">长安汽车</a><span>价格:12900</span></div> <div><img src="http://img11.360buyimg.com/n1/jfs/t4969/76/45396935/144539/347153d4/58d9cff4N36872ad6.jpg" alt="长安汽车"><a href="#">长安汽车</a><span>价格:12900</span></div> <div><img src="http://img11.360buyimg.com/n1/jfs/t4969/76/45396935/144539/347153d4/58d9cff4N36872ad6.jpg" alt="长安汽车"><a href="#">长安汽车</a><span>价格:12900</span></div> <div><img src="http://img11.360buyimg.com/n1/jfs/t4969/76/45396935/144539/347153d4/58d9cff4N36872ad6.jpg" alt="长安汽车"><a href="#">长安汽车</a><span>价格:12900</span></div> <div><img src="http://img11.360buyimg.com/n1/jfs/t4969/76/45396935/144539/347153d4/58d9cff4N36872ad6.jpg" alt="长安汽车"><a href="#">长安汽车</a><span>价格:12900</span></div> </li> <li> <div><img src="https://img14.360buyimg.com/n1/jfs/t4414/110/2582917360/207971/b7e129ad/58f0ee1fN94425de1.jpg" alt="嘉兴粽子"><a href="#">嘉兴粽子</a><span>价格:1</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t4414/110/2582917360/207971/b7e129ad/58f0ee1fN94425de1.jpg" alt="嘉兴粽子"><a href="#">嘉兴粽子</a><span>价格:1</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t4414/110/2582917360/207971/b7e129ad/58f0ee1fN94425de1.jpg" alt="嘉兴粽子"><a href="#">嘉兴粽子</a><span>价格:1</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t4414/110/2582917360/207971/b7e129ad/58f0ee1fN94425de1.jpg" alt="嘉兴粽子"><a href="#">嘉兴粽子</a><span>价格:1</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t4414/110/2582917360/207971/b7e129ad/58f0ee1fN94425de1.jpg" alt="嘉兴粽子"><a href="#">嘉兴粽子</a><span>价格:1</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t4414/110/2582917360/207971/b7e129ad/58f0ee1fN94425de1.jpg" alt="嘉兴粽子"><a href="#">嘉兴粽子</a><span>价格:1</span></div> </li> <li> <div><img src="https://img14.360buyimg.com/n1/jfs/t3079/298/5759209435/92674/14818594/587f1c33N53e5d2a9.jpg" alt="星期六"><a href="#">星期六</a><span>价格:439</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t3079/298/5759209435/92674/14818594/587f1c33N53e5d2a9.jpg" alt="星期六"><a href="#">星期六</a><span>价格:439</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t3079/298/5759209435/92674/14818594/587f1c33N53e5d2a9.jpg" alt="星期六"><a href="#">星期六</a><span>价格:439</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t3079/298/5759209435/92674/14818594/587f1c33N53e5d2a9.jpg" alt="星期六"><a href="#">星期六</a><span>价格:439</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t3079/298/5759209435/92674/14818594/587f1c33N53e5d2a9.jpg" alt="星期六"><a href="#">星期六</a><span>价格:439</span></div> <div><img src="https://img14.360buyimg.com/n1/jfs/t3079/298/5759209435/92674/14818594/587f1c33N53e5d2a9.jpg" alt="星期六"><a href="#">星期六</a><span>价格:439</span></div> </li> <li> <div><img src="https://img12.360buyimg.com/n1/jfs/t5755/127/1139389729/356866/99d4e869/5923e410Nb2983f70.jpg" alt="汇仁 肾宝片"><a href="#">汇仁 肾宝片</a><span>价格:322</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t5755/127/1139389729/356866/99d4e869/5923e410Nb2983f70.jpg" alt="汇仁 肾宝片"><a href="#">汇仁 肾宝片</a><span>价格:322</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t5755/127/1139389729/356866/99d4e869/5923e410Nb2983f70.jpg" alt="汇仁 肾宝片"><a href="#">汇仁 肾宝片</a><span>价格:322</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t5755/127/1139389729/356866/99d4e869/5923e410Nb2983f70.jpg" alt="汇仁 肾宝片"><a href="#">汇仁 肾宝片</a><span>价格:322</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t5755/127/1139389729/356866/99d4e869/5923e410Nb2983f70.jpg" alt="汇仁 肾宝片"><a href="#">汇仁 肾宝片</a><span>价格:322</span></div> <div><img src="https://img12.360buyimg.com/n1/jfs/t5755/127/1139389729/356866/99d4e869/5923e410Nb2983f70.jpg" alt="汇仁 肾宝片"><a href="#">汇仁 肾宝片</a><span>价格:322</span></div> </li> </ul> </div> <script> var title=document.getElementById('title'); var content=document.getElementById('content'); var category=title.getElementsByTagName('span'); var item=content.getElementsByTagName('li'); for (var i = 0; i < category.length; i++) { category[i].index=i; category[i].onclick=function(){ for (var j = 0; j < category.length; j++) { category[j].className=''; item[j].className=''; } this.className='select'; item[this.index].className='show'; } } </script> </body> </html>
三、js的作用域
作用域是JavaScript最重要的概念之一,想要学好JavaScript就需要理解JavaScript作用域和作用域链的工作原理。
任何程序设计语言都有作用域的概念,简单的说,作用域就是变量与函数的可访问范围,即作用域控制着变量与函数的可见性和生命周期。在JavaScript中,变量的作用域有全局作用域和局部作用域两种。
1. 全局作用域(Global Scope)
在代码中任何地方都能访问到的对象拥有全局作用域,一般来说一下几种情形拥有全局作用域:
(1)最外层函数和在最外层函数外面定义的变量拥有全局作用域
var name="yuan";
function foo(){
var age=23;
function inner(){
console.log(age);
}
inner();
}
console.log(name); // yuan
//console.log(age); // Uncaught ReferenceError: age is not defined
foo(); // 23
inner(); // Uncaught ReferenceError: inner is not defined
(2)所有末定义直接赋值的变量自动声明为拥有全局作用域,例如:
var name="yuan";
function foo(){
age=23;
var sex="male"
}
foo();
console.log(age); // 23
console.log(sex); // sex is not defined
变量blog拥有全局作用域,而sex在函数外部无法访问到。
2. 局部作用域(Local Scope)
和全局作用域相反,局部作用域一般只在固定的代码片段内可访问到,最常见的例如函数内部,所有在一些地方也会看到有人把这种作用域成为函数作用域.
如示例1中的age与inner都只有局部作用域。(js中if、for没有自己的作用域)
3.作用域链(Scope Chain)
在JavaScript中,函数也是对象,实际上,JavaScript里一切都是对象。函数对象和其它对象一样,拥有可以通过代码访问的属性和一系列仅供JavaScript引擎访问的内部属性。其中一个内部属性是[[Scope]],由ECMA-262标准第三版定义,该内部属性包含了函数被创建的作用域中对象的集合,这个集合被称为函数的作用域链,它决定了哪些数据能被函数访问。
1.示例演示
//-----**********************例1*********************************
var s=12;
function f(){
console.log(s);
var s=12; // if s=12
console.log(s)
}
f();
//-----**********************例2*********************************
var s=10;
function foo(){
console.log(s);
var s=5;
console.log(s);
function s(){console.log("ok")}// 函数的定于或声明是在词法分析时完成的,执行时已不再有任何操作
console.log(s);
}
foo();
//-----***********************例3********************************
function bar(age) {
console.log(age);
var age = 99;
var sex= 'male';
console.log(age);
function age() {
alert(123)
};
console.log(age);
return 100;
}
result=bar(5);
//-----********************************************************
2.结果分析
接下来我们就以最复杂的例3来分析整个过程。
function bar(age) {
console.log(age);
var age = 99;
var sex="male";
console.log(age);
function age(){
alert(123);
} ;
console.log(age);
return 100;
}
result=bar(5);
一 词法分析过程(涉及参数,局部变量声明,函数声明表达式):
1-1 、分析参数,有一个参数,形成一个 AO.age=undefine;
1-2 、接收参数 AO.age=5;
1-3 、分析变量声明,有一个 var age, 发现 AO 上面有一个 AO.age ,则不做任何处理
1-4 、分析变量声明,有一个 var sex,形成一个 AO.sex=undefine;
1-5 、分析函数声明,有一个 function age(){} 声明, 则把原有的 age 覆盖成 AO.age=function(){};
二 执行过程:
2-1 、执行第一个 console.log(age) 时,当前的 AO.age 是一个函数,所以输出的一个函数
2-2 、这句 var age=99; 是对不 AO.age 的属性赋值, AO.age=99 ,所以在第二个输出的age是 99;
2-3 、同理第三个输出的是 99, 因为中间没有改变 age 值的语句了。
注意:执行阶段:
function age(){
alert(123)
} ;
不进行任何操作,将执行语句复制给age这部操作是在词法分析时,即运行前完成的。