Table of contents
1. Introduction to JavaScript
-
Web standards, also known as web page standards, consist of a series of standards, most of which are formulated by W3C (World Wide Web Consortium, World Wide Web Consortium).
-
Three components:
HTML:负责网页的基本结构(页面元素和内容)。 CSS:负责网页的表现效果(页面元素的外观、位置等页面样式,如:颜色、大小等)。 JavaScript:负责网页的行为(交互效果)。
- JavaScript (abbreviation: JS) is a
跨平台、面向对象
scripting language. It is used to control the behavior of web pages, which can make web pages interactive. - JavaScript and Java are completely different languages, both in concept and design. But the underlying syntax is similar.
- JavaScript was invented by Brendan Eich in 1995 and became an ECMA standard in 1997.
- ECMAScript6 (ES6) is the most mainstream version of JavaScript (released in 2015).
2. JavaScript introduction method
Internal script:Define the JS code in the HTML page
- JavaScript code must be placed
<script></script>
between tags - In an HTML document, you can place any number of
<script>
- Generally, the script is placed at
<body>
the bottom of the element, which can improve the display speed
<script>
alert("Hello JavaScript")
</script>
建议:将<script></script>放在<body>的底部
External script:Define the JS code in an external JS file, and then introduce it into the HTML page
- In the external JS file, it only contains JS code and does not contain
<script>
tags <script>
Tags cannot be self-closing
<script src="js/demo.js"></script> √
<script src="js/demo.js"/> ×
3. JavaScript Basic Grammar
3.1 Writing Grammar
- Case Sensitivity: Like Java, variable names, function names, and everything else are case sensitive
- The semicolon at the end of each line is optional
- Notes:
- Single-line comment: // comment content
- Multi-line comment: /* comment content */
- Braces denote blocks of code
There are three output statements in JavaScript:
api | describe |
---|---|
window.alert() | warning box |
document.write() | Output content in HTML |
console.log() | write to browser console |
3.2 Variables
keywords | explain |
---|---|
was | Declare variables, global scope/function scope, allow repeated declarations |
let | Declare variables, block-level scope, no repeated declarations allowed |
const | Declare a constant, once declared, the value of the constant cannot be changed |
When declaring variables in js, you need to pay attention to the following points:
- JavaScript is a weakly typed language, and variables can store values of different types.
- Variable names need to follow the following rules:
- Constituent characters can be any letter, number, underscore (_), or dollar sign ($)
- number cannot start with
- CamelCase is recommended
3.3 Data types, operators and flow control statements
The data types in js are divided into: primitive type and reference type, specifically the following types
type of data | describe |
---|---|
number | Number (Integer, Decimal, NaN(Not a Number)) |
string | String, both single and double quotes are acceptable |
boolean | Boolean. true, false |
null | object is empty |
undefined | When a declared variable is not initialized, the default value of the variable is undefined |
The data type can be obtained using the typeof operator.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS-数据类型</title>
</head>
<body>
</body>
<script>
//原始数据类型
alert(typeof 3); //number
alert(typeof 3.14); //number
alert(typeof "A"); //string
alert(typeof 'Hello');//string
alert(typeof true); //boolean
alert(typeof false);//boolean
alert(typeof null); //object
var a ;
alert(typeof a); //undefined
</script>
</html>
Most of the operation rules in js are consistent with those in java. The specific operators are as follows:
Algorithm | operator |
---|---|
arithmetic operator | + , - , * , / , % , ++ , – |
assignment operator | = , += , -= , *= , /= , %= |
comparison operator | > , < , >= , <= , != , == , === Note that == will perform type conversion, and === will not perform type conversion |
Logical Operators | && , || , ! |
ternary operator | Conditional expression? true_value: false_value |
In js, most of the operation rules are consistent with those in java, but there is a difference between == and === in js.
- ==: only compares whether the values are equal, does not distinguish between data types, even if the types are inconsistent, == will automatically convert the type for comparison
- ===: not only compare the value, but also compare the type, if the type is inconsistent, directly return false
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS-运算符</title>
</head>
<body>
</body>
<script>
var age = 20;
var _age = "20";
var $age = 20;
alert(age == _age);//true ,只比较值
alert(age === _age);//false ,类型不一样
alert(age === $age);//true ,类型一样,值一样
</script>
</html>
Type conversion: :
- Convert string type to number:
- Convert a string literal to a number. Converts to NaN if the literal is not a number.
- Other types are converted to boolean:
- Number: 0 and NaN are false, others are true.
- String: An empty string is false, and all others are true.
- Null and undefined: Both turn to false.
Flow control statement:
Same as Java
if…else if …else…
switch
for
while
do … while
4. JavaScript functions
- Introduction: A function (method) is a block of code designed to perform a specific task.
- Definition: JavaScript functions are defined through the function keyword, and the syntax is:
//第一种方式
function functionName(参数1,参数2..){
//要执行的代码
}
//例如:
function add(a , b){
return a + b;
}
//第二种方式
var functionName = function (参数1,参数2..){
//要执行的代码
}
//例如:
var add = function(a , b){
return a + b;
}
var result = add(10,20);
alert(result);
- Notice:
- Formal parameters do not need types. Because JavaScript is a weakly typed language
- The return value does not need to define a type, you can use return directly inside the function to return
- Call: function name (actual parameter list), in JS, a function call can pass any number of parameters.
var result = add(10,20);
alert(result)
5. JavaScript objects
There are many objects in JavaScript, which can be mainly divided into the following three categories, refer to the link: W3school online learning documents
The first category: basic objects
The second category: BOM objects, mainly several objects related to browsers
The third category: DOM object, JavaScript encapsulates each tag of html into an object
5.1 Basic objects
5.1.1 Array
grammatical format
The Array object is used to define an array. There are two common syntax formats as follows:
//方式1:
var 变量名 = new Array(元素列表);
//例如:
var arr = new Array(1,2,3,4); //1,2,3,4 是存储在数组中的数据(元素)
//方式2:
var 变量名 = [ 元素列表 ];
//例如:
var arr = [1,2,3,4]; //1,2,3,4 是存储在数组中的数据(元素)
As in java, you need to 索引
get the value in the array through. The syntax is as follows:
arr[索引] = 值;
Example:
<script>
//定义数组
var arr = new Array(1,2,3,4);
var arr = [1,2,3,4];
//获取数组中的值,索引从0开始计数
console.log(arr[0]);//1
console.log(arr[1]);//2
</script>
Note:
The array in JavaScript is equivalent to the collection in Java, the length of the array is variable, and JavaScript is a weak type, so any type of data can be stored.
//特点: 长度可变 类型可变
var arr = [1,2,3,4];
arr[10] = 50;
console.log(arr[10]);//50
console.log(arr[9]);//undefined
console.log(arr[8]);//undefined
//特点: 长度可变 类型可变
var arr = [1,2,3,4];
arr[10] = 50;
arr[9] = "A";
arr[8] = true;
console.log(arr);
The browser console output is as follows:
properties and methods
Attributes:
Attributes | describe |
---|---|
length | Sets or returns the number of elements in the array. |
-
length attribute:
The length attribute can be used to get the length of the array, so we can use this attribute to traverse the elements in the array and add the following code:
var arr = [1,2,3,4]; arr[10] = 50; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
method:
method method | describe |
---|---|
forEach() | Iterate over each value element in the array and call the passed function once |
push() | Adds a new element to the end of the array and returns the new length |
splice() | remove an element from an array |
-
forEach() function
The forEach() function is used to traverse the value of the array. The parameter of this method needs to pass a function, and this function accepts a parameter, which is the value of the array when traversing.
//e是形参,接受的是数组遍历时的值 arr.forEach(function(e){ console.log(e); })
In ES6, the arrow function is introduced. The syntax is similar to the lambda expression in java. Modify the above code as follows:
arr.forEach((e) => { console.log(e); })
Note that the content without elements will not be output, because forEach will only traverse
有值的元素
. -
push() function
The push() function is used to add elements to the end of the array, where the parameter of the function is the element to be added.
Write the following code: Add 3 elements to the end of the array//push: 添加元素到数组末尾 arr.push(7,8,9); console.log(arr);
-
splice() function
The splice() function is used to delete elements in the array, and 2 parameters are filled in the function.
Parameter 1: Indicates which index position to delete from
Parameter 2: Indicates the number of deleted elements
The following code indicates: delete from index 2, delete 2 elements//splice: 删除元素 arr.splice(2,2); console.log(arr);
5.1.2 String object
There are two ways to create a String object:
//方式一
var 变量名 = new String("…");
//例如:
var str = new String("Hello String");
方式2:
var 变量名 = "…" ; //方式二
例如:
var str = 'Hello String';
Properties and Methods
Properties:
Attributes | describe |
---|---|
length | the length of the string |
-
length attribute:
The length attribute can be used to return the length of the string, add the following code:
//length console.log(str.length);
method:
method | describe |
---|---|
charAt() | returns the character at the specified position |
indexOf() | search string |
trim() | Remove spaces from both sides of a string |
substring() | Extracts characters between two specified index numbers in a string |
-
charAt()函数:
charAt()函数用于返回在指定索引位置的字符,函数的参数就是索引。添加如下代码:
console.log(str.charAt(4));
-
indexOf()函数
indexOf()函数用于检索指定内容在字符串中的索引位置的,返回值是索引,参数是指定的内容。添加如下代码:
console.log(str.indexOf("lo"));
-
trim()函数
trim()函数用于去除字符串两边的空格的。添加如下代码:
var s = str.trim(); console.log(s.length);
-
substring()函数
substring()函数用于截取字符串的,函数有2个参数。
参数1:表示从那个索引位置开始截取。包含
参数2:表示到那个索引位置结束。不包含
console.log(s.substring(0,5));
举例:
<script>
//创建字符串对象
//var str = new String("Hello String");
var str = " Hello String ";
console.log(str);
//length
console.log(str.length);
//charAt
console.log(str.charAt(4));
//indexOf
console.log(str.indexOf("lo"));
//trim
var s = str.trim();
console.log(s.length);
//substring(start,end) --- 开始索引, 结束索引 (含头不含尾)
console.log(s.substring(0,5));
</script>
浏览器执行效果如图所示:
5.1.3 JSON对象
自定义对象
其语法格式如下:
var 对象名 = {
属性名1: 属性值1,
属性名2: 属性值2,
属性名3: 属性值3,
函数名称: function(形参列表){
}
};
我们可以通过如下语法调用属性:
对象名.属性名
通过如下语法调用函数:
对象名.函数名()
举例:
<script>
//自定义对象
var user = {
name: "田天赐",
age: 10,
gender: "male",
eat: function(){
console.log("吃饭");
}
}
console.log(user.name);//田天赐
user.eat();//吃饭
<script>
json对象
JSON对象:JavaScript Object Notation,JavaScript对象标记法。是通过JavaScript标记法书写的文本。其格式如下:
{
"key":value,
"key":value,
"key":value
}
//示例:
var userStr = '{"name":"Jerry","age":18, "addr":["北京","上海","西安"]}';
其中,key必须使用引号并且是双引号标记,value可以是任意数据类型。
json这种数据格式的文本经常用来作为前后台交互的数据载体。
如下图所示:前后台交互时,我们需要传输数据,可以使用如图所示的xml格式,可以清晰的描述java中需要传递给前端的java对象。
但是xml格式存在如下问题:
- 标签需要编写双份,占用带宽,浪费资源
- 解析繁琐
所以我们可以使用json来替代,如下图所示:
类型转换:
- JSON字符串转为JS对象
var jsObject = JSON.parse(userStr);
- JS对象转为JSON字符串
var jsonStr = JSON.stringify(jsObject);
注:json字符串无法直接输出,需要先转换为json对象,才能在界面中进行显示。
value 的数据类型为:
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true 或 false)
- 数组(在方括号中)
- 对象(在花括号中)
- null
5.2 BOM对象
BOM的全称是Browser Object Model,翻译过来是浏览器对象模型。也就是JavaScript将浏览器的各个组成部分封装成了对象。我们要操作浏览器的部分功能,可以通过操作BOM对象的相关属性或者函数来完成。例如:我们想要将浏览器的地址改为http://www.baidu.com
,我们就可以通过BOM中提供的location对象的href属性来完成,代码如下:location.href='http://www.baidu.com'
BOM中提供了如下5个对象:
对象名称 | 描述 |
---|---|
Window | 浏览器窗口对象 |
Navigator | 浏览器对象 |
Screen | 屏幕对象 |
History | 历史记录对象 |
Location | d地址栏对象 |
上述5个对象与浏览器各组成对应的关系如下图所示:
5.2.1 Window对象
window对象指的是浏览器窗口对象,是JavaScript的全部对象,所以对于window对象,我们可以直接使用,并且对于window对象的方法和属性,我们可以省略window.例如:我们之前学习的alert()函数其实是属于window对象的,其完整的代码如下:
window.alert('hello');
其可以省略window. 所以可以简写成
alert('hello')
所以对于window对象的属性和方法,我们都是采用简写的方式。window提供了很多属性和方法,下表列出了常用属性和方法
window对象提供了获取其他BOM对象的属性:
属性 | 描述 |
---|---|
history | 用于获取history对象 |
location | 用于获取location对象 |
Navigator | 用于获取Navigator对象 |
Screen | 用于获取Screen对象 |
也就是说我们要使用location对象,只需要通过代码window.location
或者简写location
即可使用
window也提供了一些常用的函数,如下表格所示:
函数 | 描述 |
---|---|
alert() | 显示带有一段消息和一个确认按钮的警告框。 |
comfirm() | 显示带有一段消息以及确认按钮和取消按钮的对话框。 |
setInterval() | 按照指定的周期(以毫秒计)来调用函数或计算表达式。 |
setTimeout() | 在指定的毫秒数后调用函数或计算表达式。 |
-
alert()函数:弹出警告框,函数的内容就是警告框的内容
<script> //window对象是全局对象,window对象的属性和方法在调用时可以省略window. window.alert("Hello BOM"); alert("Hello BOM Window"); </script>
-
confirm()函数:弹出确认框,并且提供用户2个按钮,分别是确认和取消。
添加如下代码:var flag = confirm("您确认删除该记录吗?"); alert(flag);
-
setInterval(fn,毫秒值):定时器,用于周期性的执行某个功能,并且是循环执行。该函数需要传递2个参数:
fn:函数,需要周期性执行的功能代码
毫秒值:间隔时间
代码如下://定时器 - setInterval -- 周期性的执行某一个函数 var i = 0; setInterval(function(){ i++; console.log("定时器执行了"+i+"次"); },2000);
-
setTimeout(fn,毫秒值) :定时器,只会在一段时间后执行一次功能。参数和上述setInterval一致
代码如下://定时器 - setTimeout -- 延迟指定时间执行一次 setTimeout(function(){ alert("JS"); },3000); 浏览器打开,3s后弹框,关闭弹框,发现再也不会弹框了。
5.2.2 Location对象
location是指代浏览器的地址栏对象,对于这个对象,我们常用的是href属性,用于获取或者设置浏览器的地址信息,添加如下代码:
//获取浏览器地址栏信息
alert(location.href);
//设置浏览器地址栏信息
location.href = "https://www.baidu.com";
浏览器效果如下:首先弹框展示浏览器地址栏信息,
然后点击确定后,因为我们设置了地址栏信息,所以浏览器跳转到百度。
5.3 DOM对象
DOM:Document Object Model 文档对象模型。也就是 JavaScript 将 HTML 文档的各个组成部分封装为对象。
DOM之前在学习 XML 就接触过,只不过 XML 文档中的标签需要我们写代码解析,而 HTML 文档是浏览器解析。封装的对象分为
- Document:整个文档对象
- Element:元素对象
- Attribute:属性对象
- Text:文本对象
- Comment:注释对象
如下图,上面是 HTML 文档内容,下面是 DOM 树:
主要作用如下:
- 改变 HTML 元素的内容
- 改变 HTML 元素的样式(CSS)
- 对 HTML DOM 事件作出反应
- 添加和删除 HTML 元素
总而达到动态改变页面效果目的,具体我们可以查看代码中提供的06. JS-对象-DOM-演示.html来体会DOM的效果。
5.3.1 获取DOM对象
DOM的作用是通过修改HTML元素的内容和样式等来实现页面的各种动态效果,但是要操作DOM对象的前提是先获取元素对象,然后才能操作。所以学习DOM,主要的核心就是学习如下2点:
- 如何获取DOM中的元素对象(Element对象 ,也就是标签)
- 如何操作Element对象的属性,也就是标签的属性。
接下来我们先来学习如何获取DOM中的元素对象。
HTML中的Element对象可以通过Document对象获取,而Document对象是通过window对象获取的。document对象提供的用于获取Element元素对象的api如下表所示:
函数 | 描述 |
---|---|
document.getElementById() | 根据id属性值获取,返回单个Element对象 |
document.getElementsByTagName() | 根据标签名称获取,返回Element对象数组 |
document.getElementsByName() | 根据name属性值获取,返回Element对象数组 |
document.getElementsByClassName() | 根据class属性值获取,返回Element对象数组 |
5.4 JavaScript事件
HTML事件是发生在HTML元素上的 “事情”,例如:
- 按钮被点击
- 鼠标移到元素上
- 输入框失去焦点
- …
而我们可以给这些事件绑定函数,当事件触发时,可以自动的完成对应的功能。这就是事件监听。
5.4.1 事件绑定
JavaScript对于事件的绑定提供了2种方式:
-
方式1:通过html标签中的事件属性进行绑定
例如一个按钮,我们对于按钮可以绑定单机事件,可以借助标签的onclick属性,属性值指向一个函数。
<input type="button" id="btn1" value="事件绑定1" onclick="on()">
很明显没有on函数,所以我们需要创建该函数,代码如下:
<script> function on(){ alert("按钮1被点击了..."); } </script>
浏览器打开,然后点击按钮,弹框如下:
-
方式2:通过DOM中Element元素的事件属性进行绑定
According to the knowledge points we have learned about DOM, we know that tags in html are loaded into element objects, so we can also manipulate the attributes of tags through the attributes of element objects. At this point we add a button again, the code is as follows:
<input type="button" id="btn2" value="事件绑定2">
We can first obtain the button object through the id attribute, and then manipulate the onclick attribute of the object to bind the event. The code is as follows:
document.getElementById('btn2').onclick = function(){ alert("按钮2被点击了..."); }
The browser refreshes the page, clicks the second button, and the pop-up box is as follows:
It should be noted that the function bound to the event will only be called when the event is triggered.
5.4.2 Common events
event attribute name | illustrate |
---|---|
onclick | mouse click event |
onblur | element loses focus |
onfocus | element gets focus |
onload | A page or image has finished loading |
onsubmit | This event fires when the form is submitted |
onmouseover | The mouse is moved over an element |
onmouseout | Mouse out of an element |