1.初级
1.1 JS的使用方法
1 2 3 4 5 6 7 8 //第一种:写在head标签里 //不推荐头部使用:根据代码运行是自上而下解释的特性,会先解析head标签里JS,然后才解析元素,故需要监听 //需添加 window.onload <script > window .onload = function ( ) { alert(123 ); } </script >
1 2 3 4 //第二种:写在body结束标签上面 <script > alert(123); </script >
1 2 3 4 5 6 7 8 9 //第三种:外部导入JS文件 //写在body结束标签上面的内容 <script src ="demo.js" > </script > //写在.js文件中的内容 alert(123);
栗子:
1 2 3 4 5 6 7 8 9 <body > <p > Hello world!</p > <script src ="demo.js" > </script > <script > console .log(123 ); </script > </body >
1.2 JS获取元素的方法
在js中想要操作元素,或者说执行一些行为,首先需要获取到对应的元素。才能进行下一步的操作,所以要首先学会如何获取元素
1 2 3 4 //JS获取独有标签 document.title 获取标题 document.head 获取头部信息 document.body 获取body内容
1 2 3 4 5 6 7 8 //其他标签的获取 通过id获取元素:document.getElementById("idname"); 通过class获取元素:document.getElementsByClassName("classname"); 通过标签名获取元素:document.getElementsByTagName("tagdem"); 表单中的name:document.getElementsByName("name"); selector选择器(不兼容IE7及以下): document.querySelector (""); 通过CSS选择器获取一个 document.querySelectorAll(""); 通过CSS选择器获取所有
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS获取元素的方法</title > <style > #p1{} .p2{} </style > </head > <body > <p id ="p1" class ="p2" > 我是段落标签1</p > <p class ="p2" > 我是段落标签2</p > <p name ="p3" > 我是段落标签3</p > <script > var oP = document .getElementById("p1" ) console .log(oP); var oP = document .getElementsByClassName("p2" )[1 ]; console .log(oP); var oP = document .getElementsByClassName("p2" ); console .log(oP[1 ]); var oP = document .getElementsByTagName("p" ); console .log(oP[2 ]); var oP = document .getElementsByName("p3" ); console .log(oP[0 ]); var oP = document .querySelector("#p1" ); var oP = document .querySelector(".p2" ); console .log(oP[0 ]); var oP = document .querySelectorAll(".p2" ); console .log(oP[1 ]); </script > </body > </html >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 //获取嵌套元素 <body > <p id ="p1" CLASS ="p2" > 我是段落标签4 <span > 111111</span > </p > <script > var oP = document .getElementById("p1" ); var oP1 = oP.getElementsByTagName("span" ); console .log(oP1[0 ]); </script >
1.3 JS的基本事件
事件含义:所谓事件,是指JavaScript捕获到用户的操作,并做出正确的响应
使用:在事件函数里而,有一个关键字this,代表当前发事件的这个元素。事件通过函数完成,在函数内部书写自己想要实现的效果
1 2 3 4 5 //鼠标事件 左键单击 onclick 左键双击 ondblclick 鼠标移入 onmouseover/onmouseenter 鼠标移出 onmouseout/onmouseleave
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS基本事件</title > <style > div { width : 200px ; height : 200px ; border : 1px solid red; } </style > </head > <body > <p id ="p1" CLASS ="p2" > 我是段落标签1</p > <p class ="p2" > 我是段落标签2</p > <p name ="p3" > 我是段落标签3</p > <div > 111 </div > <script > var oP = document .getElementById("p1" ); oP.onclick = function ( ) { oP.innerHTML = '<h1>我不是段落标签1</h1>' } oP.ondblclick = function ( ) { oP.innerHTML = '<h1>我不是段落标签1</h1>' } var oP1 = document .getElementsByTagName("div" )[0 ]; oP1.onmouseenter = function ( ) { oP1.innerText = "byebye" ; } oP1.onmouseleave = function ( ) { oP1.innerText = "hello" ; } </script > </body > </html >
1.4 JS修改样式
js可以修改规范和不规范的标签的样式,也可以配合点击事件等一起使用
1 2 .style.height 单个样式修改 .style.cssText 多个样式修改
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS修改样式</title > <style > div { width : 200px ; height : 200px ; border : 1px solid red; background-color : #3A87CD ; } </style > </head > <body > <div > 111 </div > <script > var obox = document .querySelector("div" ); obox.onclick = function ( ) { obox.style.width = "100px" ; obox.style.height = "100px" ; obox.style.background = "red" ; } </script > </body > </html >
1.5 JS操作标签属性
1 2 3 4 5 6 7 8 规范的标签属性: . 符号直接操作(可读可写) .id 修改id .className 修改class 不规范(自定义)的标签属性: 获取: .getAttribute() 设置: .setAttribute() (增/添) 移除: .removeAttribute() (删) 判断: .hasAttribute()
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS操作标签属性</title > <style > div { width : 200px ; height : 200px ; border : 1px solid red; background-color : #3A87CD ; } </style > </head > <body > <div id ="box1" > </div > <script > var obox = document .querySelector("div" ); console .log(obox.id); obox.id = "box1" ; console .log(obox.id); obox.className = "box2" ; obox.className = "box3" ; console .log(obox.className); obox.removeAttribute("class" ); obox.setAttribute("abc" ,"abc1" ); obox.setAttribute("class" ,"abc1" ); obox.setAttribute("abc" ,"abc2" ); console .log(obox.hasAttribute("class" )); obox.removeAttribute("class" ); </script > </body > </html >
1.6 JS与CSS分离
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS与CSS分离</title > <style > div { width : 200px ; height : 200px ; border : 1px solid red; background-color : #3A87CD ; } .box1 { width : 100px ; height : 100px ; background : red; } </style > </head > <body > <div > </div > <script > var obox = document .querySelector("div" ); obox.onclick = function ( ) { obox.setAttribute("class" ,"box1" ); } </script > </body > </html >
1.7 JS的基本数据类型
1 2 3 4 5 6 7 8 9 number 数字 string 字符串 boolean 布尔型 undefined 未定义 null 空(对象) object 对象 前五个是简单数据类型,最后一个是复杂数据类型 typeof x 显示数据类型
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS基本数据类型</title > </head > <body > <script > var a = 123 ; console .log(typeof a); var b = "123" ; console .log(typeof b); var c = true ; console .log(typeof c); var d; console .log(typeof d); var e = null ; console .log(typeof e); var f = [1 ,2 ,3 ,4 ,5 ]; console .log(typeof f); </script > </body > </html >
2.提升
2.1 JS运算符
算术运算符
算术运算符(基础数字运算) + - * / %
当不是数字之间的运算的时候,+号两边一旦有字符串(引号引起的部分),那么+号就不再是数学运算了,而是拼接,最终结果是字符串。
-/*% 尽量将字符串转换成数字(隐式类型转换)
NaN: Not a Number number
赋值运算符
+= -= = /= = 这些是基本的赋值运算符,除此之外还有 *++ --**,这两个都存在隐式类型转换,会全部转成数字。
逻辑运算符
JS中的逻辑运算用:&&、||、! 来表示。
&& 和 || 不会进行类型转换,!则会进行类型转换,将后面的数据先转换为布尔型在取反
比较运算符
< != >= <= == ===
如果等号两边是boolean、string、number三者中任意两者进行比较时,优先转换为数字进行比较。
如果等号两边出现了null或undefined,null和undefined除了和自己相等,就彼此相等
NaN==NaN 返回false,NaN和所有值包括自己都不相等。
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS运算符</title > </head > <body > <script > document .write(1 + '2' + "<br/>" ); document .write(1 - '2' + "<br/>" ); document .write(1 + true + "<br/>" ); document .write(1 + null + "<br/>" ); document .write(1 + undefined + "<br/>" ); var a = 1 ; var b = null ; document .write(a++ +"<br/>" ); document .write(a +"<br/>" ); document .write(++a +"<br/>" ); document .write(++b +"<br/>" ); document .write(('2' == 2 ) + "<br/>" ); document .write(('2' === 2 ) + "<br/>" ); document .write((2 >3 &&2 <5 ) + "<br/>" ); document .write((2 >3 ||2 <5 ) + "<br/>" ); document .write(!(2 >3 &&2 <5 ) + "<br/>" ); </script > </body > </html >
2.2 JS流程控制
JS中流程控制是if判断和switch选择
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS流程控制</title > </head > <body > <script > var food = "山竹" ; if (food == "dinner" ) { document .write("真饱!" ); } else if (food == "山竹" ){ document .write("我吃了,但没吃饱!" ); } else { document .write("好饿!" ); } var a = 1 ; a>1 ?console .log(a+1 ):console .log(a+3 ); var day = 1 ; switch (day){ case 1 : document .write("今天星期一" ); break ; case 2 : document .write("今天星期二" ); break ; case 3 : document .write("今天星期三" ); break ; case 4 : document .write("今天星期四" ); break ; case 5 : document .write("今天星期五" ); break ; case 6 : document .write("今天星期六" ); break ; case 7 : document .write("今天星期日" ); break ; } var sex = "girl" ; switch (sex){ case "girl" : document .write("她是女孩。" ); break ; case "boy" : document .write("他是男孩。" ); break ; default : document .write("写错啦!" ); } </script > </body > </html >
2.3 JS循环
for循环
while循环
while (expression){ statement }
while是一个基本的循环语句,expression为真的时候,就会执行循环体
do…while循环
do…while和while类似,只是会先执行一个循环
for in语句
JS中的for也支持类似于python中的用法,可以遍历对象所有的属性。
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS循环</title > </head > <body > <script > for (var i=1 ; i<=10 ; i++){ document .write("我是" + i + "号<br/>" ); } for (var i=1 ;i<=10 ;i++) { if (i==6 ){ continue ; } document .write("我是" + i + "号<br/>" ); } var i = 1 ; while (i<=5 ){ document .write(i + "<br/>" ); i++; } var i = 1 ; do { document .write(i + "<br/>" ); i++; }while (i<1 ); var array = [1 ,2 ,3 ,4 ,5 ]; for (var i in array){ document .write(i + " " ,array[i] + "<br/>" ) } </script > </body > </html >
2.4 JS字符串方法
length 长度;slice 切片;substring 截取
indexOf 索引;split 分割;replace 替换
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS字符串方法</title > </head > <body > <script > var str = "hello world!" console .log(str.length); console .log(str.slice(1 , 4 )); console .log(str.substring(1 , 4 )); console .log(Object .key(str)); </script > </body > </html >
2.5 数组方法
length 长度 ;push 追加;unshift 添加
pop,shift 删除;indexOf 查找
改:slice 切片, join 拼接, sort 正向排序, reverse 反向无排序
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 数组方法</title > </head > <body > <script > var array = ["橘子" ,"苹果" ,"香蕉" ,"栗子" ]; array[1 ] = "葡萄" ; console .log(array.length); console .log(array.slice(1 , 3 )); var arr = ['a' ,'c' ,'b' ,'g' ,'d' ]; console .log(arr.reverse()); console .log(array.join('-' )); </script > </body > </html >
2.6 JS循环练习
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <!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 > <li > 444</li > </ul > <script > var oli = document .querySelectorAll("ul li" ); for (var i=0 ; i<oli.length;i++){ oli[i].onclick = function ( ) { alert(i); } } </script > </body > </html >
解决alert(i);的办法:
解决办法1: var定义的全局变量i 换成局部变量 let
解决办法2:利用index_num存储下标值
1 2 3 4 5 6 7 8 9 10 <script > var oli = document .querySelectorAll("ul li" ); for (let i=0 ; i<oli.length;i++){ oli[i].onclick = function ( ) { alert(i); } } </script >
1 2 3 4 5 6 7 8 9 10 11 12 <script > var oli = document .querySelectorAll("ul li" ); for (var i=0 ; i<oli.length;i++){ oli[i].index_num = i; oli[i].onclick = function ( ) { alert(this .index_num); } } </script >
3.进阶
3.1 JS的内置对象
JS内部已经内置了不少对象,类似于Python中的内置模块,可以直接使用,并且对象一般不需要导入,可以直接使用。
Math对象是一个处理数学相关的对象,可以用来执行在数学相关的内容
1 2 3 4 5 6 7 8 9 10 Math.sqrt (4 ) Math.abs (-7 ) Math.PI Math.pow (2 , 2 ) Math.round(3.6 ) Math.ceil (3.4 ) Math.floor (3.6 ) Math.max(3 , 1 , 7 , 9 ) Math.min(2 , 1 , 5 , 6 ) Math.random()
1 2 3 4 console.log (Math.random()); console.log (Math.random()*100 ); console.log (Math.round(Math.random()*100 ));
日期对象也是常用对象之一,基本和常用的方法都是需要了解和熟悉
1 2 3 4 5 6 7 8 9 10 11 12 13 var today = new Date(); var year = today.getFullYear(); var month = today.getMonth(); var date = today.getDate(); var day = today.getDay(); var hour = today.getHours(); var min = today.getMinutes(); var sec = today.getSeconds(); document.write("现在是北京时间:" +year+"年" +month+"月" +date+"日" +hour+":" +min+":" +sec+"<br/>" )
1 2 3 4 5 6 7 8 9 10 var timestan = Date.now(); document.write(timestan);
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS的内置对象</title > </head > <body > <script > console .log(Math .sqrt(4 )); console .log(Math .abs(-7 )); console .log(Math .PI); console .log(Math .pow(2 , 2 )); console .log(Math .round(3.6 )); console .log(Math .ceil(3.4 )); console .log(Math .floor(3.6 )); console .log(Math .max(3 , 1 , 7 , 9 )); console .log(Math .min(2 , 1 , 5 , 6 )); console .log(Math .random()); console .log(Math .random()*100 ); console .log(Math .round(Math .random()*100 )); var today = new Date (); console .log(today); var year = today.getFullYear(); console .log(year); var month = today.getMonth(); console .log(month); var month = today.getMonth()+1 ; console .log(month); var day = today.getDay(); console .log(day); var date = today.getDate(); console .log(date); var hour = today.getHours(); console .log(hour); var min = today.getMinutes(); console .log(min); var sec = today.getSeconds(); console .log(sec); document .write("现在是北京时间:" +year+"年" +month+"月" +date+"日" +hour+":" +min+":" +sec+"<br/>" ) var timestan = Date .now(); document .write(timestan); </script > </body > </html >
3.2 JS的Window对象
Window对象是所有客户端JS特性和API的主要接入点。它表示Web浏览器的一个窗口或窗体,并且可以用标识符window来引用它。
Window对象定义了一些属性和方法,比如:alert()方法、非常重要的document属性 等
计时器 就是Window中的一个方法,可以用来实现计时的一些操作。
1 2 3 4 5 6 7 8 9 10 setTimeout(function (){ console.log (123 ); },1000 ); setInterval(function (){ console.log (321 ); },1000 );
1 2 3 4 5 6 7 8 9 10 11 var timer1 = setTimeout(function (){ console.log (123 ); },1000 ); clearTimeout(timer1); var timer2 = setInterval(function (){ console.log (321 ); },1000 ); clearInterval(timer2);
定时器可以实现定时操作,并且通过window对象来实现跳转操作
1 2 3 4 5 6 7 var w = window.open(); var w = window.open("demo.html" ,"haha" ,"width=300,height=200" ); w.alert("hello!" ); w.location = "https://www.bilibili.com/" ; w.close();
3.3 JS的函数
JS 的函数包裹在花括号当中,使用关键词function来定义。函数可以挂载在一个对象上,作为一个对象的属性,称为对象的方法。
JS函数特性:在JS中,函数即对象,程序可以随意操控它们。比如,JS可以把函数赋值给变量,或者作为参数传递给其他的函数,甚至可以设置属性,调用它们的方法。
JS有名函数和匿名函数
1 2 3 4 5 6 7 8 9 10 function func () { console.log (1 ); } func(); document.onclick = function (){ console.log (2 ); }
函数的参数/传参
1 2 3 4 5 6 7 8 9 10 function func (x) { console.log (x); } func(3 ); function sum (x,y) { console.log (x + y); } sum(1 ,7 );
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 function add (x,y) { console.log (x, y); console.log (arguments); } add(1 ); add(2 ,3 ); add(1 ,2 ,3 ); function add1 () { for (var i=0 ; i<arguments.length;i++) { console.log (arguments[i]); } for (var i in arguments){ document.write(i); } } add1(1 ,3 ,5 ,7 ,9 );
函数的分类
1 2 3 4 5 6 7 var a = alert(1 ); console.log (a); var b = console.log (2 ); console.log (b);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 var oBox = document.querySelector("div" ); console.log (oBox); function func1 () { console.log (8 ); } var a = func1(); console.log (a); function func2 () { console.log (1 ); return "我返回了" ; } var a = func2(); console.log (a); function func3 () { console.log (7 ); return "我返回了" ; console.log (3 ); } var a = func3(); console.log (a);
函数的作用域
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 var a = 100 ; function func () { var a = 200 ; alert(a); } alert(a); func(); alert(a); var a = 100 ; function func () { a = 200 ; alert(a); } alert(a); func(); alert(a); var a = 100 ; function func1 () { var a = 200 ; function func2 () { var a = 300 ; } func2(); alert(a); } alert(a); func1(); alert(a); var a = 100 ; function func1 () { var a = 200 ; function func2 () { a = 300 ; } func2(); alert(a); } alert(a); func1(); alert(a);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 { var i = 1 ; } console.log (i); { let j = 2 ; console.log (j); }
自定义函数
1 2 3 4 5 6 7 8 9 ~function (){ console.log (1 ); }(); +function (){ console.log (1 ); }(); -function (){ console.log (1 ); }();
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS函数</title > </head > <body > <div > </div > <script > var oBox = document .getElementsByTagName("div" ); function func ( ) { alert(1 ); }; oBox.onclick = func; </script > </body > </html >
3.4 JS异常
写代码会出现或多或少的错误,而出现错误就会终止代码的运行;能不能在可能出现错误的代码它不出现错误或执行自己写的错误
提供一些异常处理机制,具有一部分异常恢复能力
1 2 3 4 5 6 7 8 9 try { }catch (e){ alert(e); throw new Error("太胖了!" ); }finally{ }
栗子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > JS异常</title > </head > <body > <button id ="btn" onclick ="func()" > 点我</button > <script > function func ( ) { try { alert("我是" +num); }catch (e){ alert("错误类型:" +e.name+" 错误信息:" +e.message); }finally { alert("我已经执行完毕" ); } } function func ( ) { var num = 123 ; try { if (num<100 )throw "太小了" ; if (num==100 )throw "刚昂好" ; if (num>100 )throw "太大了" ; }catch (e){ alert(e); }finally { alert("我已经执行完毕" ); } } </script > </body > </html >
4.练习