1. What is JavaScript
2. Quick start
2.1. Introducing JavaScript
1. Internal label
<script> //. . . . . </script>
2. External introduction
abs.js
//. . . .
test.html
<script src="abs,js"></script>
Test code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--scrpt Inside the label, write JavaScript code--> <!-- <script>--> <!-- alert('hello');--> <!-- </script>--> <!-- External label--> <!-- be careful: script Must appear in pairs--> <script src="js/qj.js"></script> <!--No definition type,It also defaults to JavaScript--> <script trpe="text/javascript"></script> </head> <body> <!--You can also put it here--> </body> </html>
2.2 introduction to grammar
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- Strictly case sensitive--> <script> //1. Define variable type variable name = variable value; var num = 1; //alert(num); //2. Condition control if(2>1){ alert("true"); } //console.log(score) prints variables on the browser console </script> </head> <body> </body> </html>
2.3 data type
number
js does not distinguish between decimal and integer, Number
123 // Integer 123 123.1 // Floating point number 123.1 1.23e3 // Scientific counting method -99 // negative NaN // not a number Infinity // Represents infinity
character string
'abc' "abc"
Boolean value
true false
Logical operator
&&
||
!
Comparison operator
= == be equal to(Different types have the same value. It will also be judged as true) === Absolutely equal to(The type is the same, the value is the same, and the result is true)
This is js a defect. Try not to use = = comparison
Notice:
- NaN===NaN, which is not equal to all values, including itself
- It can only be judged by isNaN(NaN)
Floating point problem
console.log(1/3===(1-2/3))
Try to avoid using floating point numbers for operations
console.log(Math.abs(1/3-(1-2/3))<0.0000000001)
null and undefined
- Null null
- Undefined undefined
array
//To ensure code readability, try to use [] var arr=[1,2,3,4,"heel",null] new Array(1,2,3,"hello",null)
Fetch array subscript: if out of bounds, undefined
object
The object is a brace and the array is a bracket []
Each attribute is separated by commas, and the last one is not required
var person={ name:"gx", age:18, tags:['java','yd','...'] }
Value
person.name;
2.4. Strictly check the format
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 'use strict'Strict inspection mode and Prevention JavaScript Randomness of Local variables are recommended ler To define It must be written on the first line --> <script> 'use strict' //global variable let i=1; </script> </head> <body> </body> </html>
3. Data type
3.1 string
- Use single or double quotation marks normally
- Note escape characters
\' \n \t \u#### unicode characters \x41 Ascll character
- Multiline string writing
//tab above var msg=`hello world aaaa`
- Template string
let name="gx"; let age=18; let msg=`nihao,${name}`
- String length
str.length
-
Immutability of string
-
toggle case
//Note that this is a method, not a property student.toUpperCase() student.toLowerCase()
- sutdent.indexOf() get subscript
- student.substing()
//[), including left, excluding right student.substing(1) //Intercept from first character to last character student.substing(1,3) //Include the first and not the bottom three
3.2 array
Array can contain any type
1. Length
arr.length
Note: if you assign an value to arr.length, the size of the array will change. If the value is too small, the elements will be lost
2. indexOf, subscript index
The string "1" is different from the number 1
3. slice() intercepts part of the Array and returns a new Array, similar to String's substituting()
4. pop() is pressed into the tail and push() into the head
5. unshift() press in head, shift()yaruweibu
6. sort()
7. Element reverse()
8. Add an array at the end of concat()
- Array was not modified
9. Connector join
- Print a tiled array, concatenated with specific characters
3.3 object
Several key value pairs
var Object name={ Attribute name: attribute value, Attribute name: attribute value, Attribute name: attribute value } //Defines a person object var person={ name:"gao", age:18, email:"11111@qq.com", score:0 }
js object, {...} represents an object. The key value describes the attribute xxx: xxx. Commas are used between multiple attributes, and the last attribute is not added with commas
1. Object assignment
person.name="gx"
2. If you use a non-existent object attribute, no error will be reported
person.haha undefined
3. Dynamically delete attributes, and delete object attributes through delete
delete person.name
4. To add an attribute, simply add a value to the new attribute
person.haha="haha"
5. Determine whether the attribute value is in the object
'age' in person //inherit 'toString' in person
6. Judge whether a property itself has this object hasOwnProperty()
person.hasOwnProperty('toString') false person.hasOwnProperty('age') true
3.4 process control
if judgment
loop
var age=[12,3,12,1,45,6,7,945,3] //function age.forEach(function (value){ console.log(value) })
3.5. Map and set
Map:
var map =new Map([['qq',100],['ww',90],['ee',80]]); var name=map.get('qq'); map.add('aa',1111);//newly added map.delete('qq');//delete console.log(name);
Set: unordered non repeating set
set.add(2);//add to set.delete(1);//delete console.log(set.has(3));//Include an element
3.6,iterator
//Via for of var arr=[3,4,5] for(var x of arr){ console.log(x) }
Traversal map
var map = new Map([['qq', 100], ['ww', 90], ['ee', 80]]); for (let x of map) { console.log(x) }
Traversal Set
var set = new Set([1, 2, 3]) for (let x of set) { console.log(x) }
4. Functions
4.1. Define function
Defined in
function abs(x){ if(x>0){ return x; }else{ return -x; } }
Once executed, return represents the end of the function
If return is not executed, the function will also return after execution, and the result is undefined
Definition mode 2
Anonymous function
var abs = function(x){ if(x>0){ return x; }else{ return -x; } }
Call function
abs(10) abs(-10)
javaScript can pass arbitrary parameters or no parameters
How to avoid without parameter transmission
- Throw exception manually
var abs = function (x) { //Throw exception manually if (typeof x !== 'number') { throw 'not a number' } if (x > 0) { return x; } else { return -x; } }
arguments
Represents that all parameters passed in are an array
var abs = function (x) { console.log("x=>" + x); for (var i = 0; i < arguments.length; i++) { console.log(arguments[i]); } if (x > 0) { return x; } else { return -x; } }
rest
Get all parameters except processing parameters
function aaa(a,b,...rest){ console.log("a=>"+a); console.log("b=>"+b); console.log(rest); }
The rest parameter can only be written at the end and identified with
4.2 variable scope
In JavaScript, variables defined by var actually have scope.
Declared in the function body, cannot be called outside the function body
function qj(){ var x=1; x=x+1; } x=x+2;
If two functions use the same variable name, there is no conflict as long as they are inside the function
function qj(){ var x=1; x=x+1; } function qj2(){ var x='A'; x=x+1; }
Internal functions can access external function members, while external functions cannot access internal members
Internal and external function variable names are the same
function qj(){ var x=1; function qj2(){ var x='A'; console.log('inner'+x); } console.log('outer'+x); qj2(); } qj() //Output results: //outer1 //innerA
In JavaScript, function variables are searched from the inside to the outside. If there is a function variable with the same name outside, the internal function will shield the external function variables
Promote variable scope
function qj(){ var x="x"+y; console.log(x); var y='y'; } qj();
Result: xundefined
Note: js automatically promotes the declaration of y, but does not promote the assignment of y
All variables are defined in the function header
global variable
By default, all global variables are automatically bound under the window object
alert() itself is also a window variable
var x='xxx'; window.alert(x); var old_alert=window.alert; //old_alert(x); window.alert=function (){ } //alert failed window.alert(123); //recovery window.alert=old_alert; window.alert(456);
JavaScript actually has only one scope. If any variable (the function will also be regarded as a variable) is not found in the function scope, it will be found in the global scope. If not, an error will be reported
standard
Because all global variables are bound to the window, if different js files use the same global variable, it will conflict. In order to reduce the conflict, the global variable will be bound to the only global variable
//Unique global variable var gaoApp={}; //Define global variables gaoApp.name="gx"; gaoApp.add=function(a,b){ return a+b; }
Local scope
function aaa(){ for(var i=0;i<100;i++){ console.log(i); } console.log(i+1);//101 }
let keyword, in order to reduce local conflicts
function aaa(){ for(let i=0;i<100;i++){ console.log(i); } console.log(i+1);//Uncaught ReferenceError: i is not defined }
constant
4.3 method
The method is to put the function inside the object
var gx={ name:"gao", birth:1999, age:function (){ var now=new Date().getFullYear(); return now-this.birth; } } //call gx.age()
Write separately
function getAge(){ var now=new Date().getFullYear(); return now-this.birth; } var gx={ name:"gao", birth:1999, age:getAge }
5. Object
5.1,Date
Basic use
var now=new Date(); now.getFullYear(); now.getMonth(); now.getDate(); now.getDay(); now.getHours(); now.getMinutes(); now.getSeconds(); now.getTime();
5.2,JSON
In JavaScript, everything is an object, and any type supported by js can be represented by JSON; number,string
Format:
- Object with {}
- Array with []
- All key value pairs use key: value
JSON string and js conversion
var user={ name:"gx", age:3, sex:"man" } //Object to JSON string var jsonUser=JSON.stringify(user); //Convert json brace string to object var obj=JSON.parse('{"name":"gx","age":3,"sex":"man"}');
6. Object oriented programming
Prototype object
Classes: Templates
Object: specific performance
Prototype:
var Student={ name:"gx", age:3, run:function (){ console.log(this.name+"run...") } } var xiaoming={ name:"xiaoming" } //Prototype object xiaoming.__proto__=Student; var Bird={ fly:function (){ console.log(this.name+"fly...") } } xiaoming.__proto__=Bird;
function Student(name){ this.name==name; } //Adding methods to student s Student.prototype.hello=function (){ alert("hello") }
class inheritance
//After ES6 //Define a student class class Student{ constructor(name) { this.name=name; } hello(){ alert("hello") } } var xiaoming=new Student("xiaoming");
inherit
class Student{ constructor(name) {//structure this.name=name; } hello(){ alert("hello") } } class xiaoStudent extends Student{ constructor(name,grade) { super(name); this.grade=grade; } myGrade(){ alert('pupil') } } var xiaoming=new Student("xiaoming"); var xiaohong=new xiaoStudent("xiaohong",1);
Prototype chain
__ proto __
7. Operation BOM object (key)
Browser introduction
BOM: Browser Object Models
- IE 6~11
- chrome
- Safati
- FireFox
Third party
QQ browser
window
Window stands for browser window
window.alert(1) undefined window.innerHeight 460 window.innerWidth 2144 window.outerHeight 1173 window.outerWidth 2151 //Browser window
Navigator
Navigator encapsulates the browser's information
screen
screen.width 2144 screen.height 1206
Location (important)
location represents the URL information of the current page
host: "newtab.firefoxchina.cn" href: "https://newtab.firefoxchina.cn/newtab/as/activity-stream.html" protocol: "https:" //Set new address location.assign()
document
document represents the current page
document.title
Get the specific document tree node
<dl id="app"> <dt>java</dt> <dd>javaSE</dd> <dd>javaEE</dd> </dl> <script> var d1 = document.getElementById('app'); </script>
Get cookie
document.cookie
The server can set a cookie: httpOnly
history
History represents the history of the browser
history.back()//back off history.forward()//forward
8. Manipulating DOM objects (focus)
DOM: text object model
core
- Update: updating DOM nodes
- Traversing DOM nodes: get DOM nodes
- Delete: deletes a DOM node
- Add: add a DOM node
To operate a DOM node, you must first obtain the DOM node
<div id="father"> <h1>Title I</h1> <p id="p1">p1</p> <p class="p2">p2</p> </div> <script> var h1 = document.getElementsByTagName("h1") var p1 = document.getElementById("p1") var p2 = document.getElementsByClassName("p2") var father = document.getElementById("father") </script>
Update node
<div id="id1"> </div> <script> var id1=document.getElementById("id1") </script>
-
==id1.innerText = "123" = = modify the value of the text
-
==id1. InnerHTML = "< strong > 123 < / strong >" = = HTML text tags can be parsed
-
==id1.style.color = 'red' = = modify color
-
==id1.style.fontSize = '200px' = = modify size
Delete node
Step: get the parent node first, and then delete the child node
<div id="father"> <h1>Title I</h1> <p id="p1">p1</p> <p class="" P2>p2</p> </div> <script> var self=document.getElementById("p1") var father =p1.parentElement; father.removeChild(self) </script> //Deletion is a dynamic process; When a node is deleted, the children are always changing father.removeChild(father.children[0])
Insert node
We get a DOM node. If the DOM is empty, we can use innerHTML to add an element
If the DOM is not empty, use:
- appendChild added, node already exists
<p id="js">javascript</p> <div id="list"> <p id="se">JavaSE</p> <p id="ee">javaEE</p> <p id="me">javaME</p> </div> <script> var js=document.getElementById('js'); var list=document.getElementById('list') list.appendChild(js) </script>
- Create a node
<head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="" type="text/css"> <script type="text/javascript" src=""></script> </head> <body> <p id="js">javascript</p> <div id="list"> <p id="se">JavaSE</p> <p id="ee">javaEE</p> <p id="me">javaME</p> </div> <script> var js = document.getElementById('js'); var list = document.getElementById('list') //Create a node through js var newP = document.createElement("p")//Create a label p newP.id = "newp"; newP.innerText = "aaa" //list.appendChild(newP) newP.setAttribute('id','newP') var myScript=document.createElement('script') myScript.setAttribute('type','text/javascript') //Create a style label var myStyle=document.createElement('style')//Create an empty style tag myStyle.setAttribute("type",'text/css'); myStyle.innerHTML='body{background-color:chartreuse}';//Set label content document.getElementsByTagName('head')[0].appendChild(myStyle) </script> </body>
insert
<script> var ee = document.getElementById('ee') var js = document.getElementById('js') var list = document.getElementById('list') list.insertBefore(js, ee) </script>
9. Action form (validation)
What is a form DOM tree
<form action="post"> <p> <span>user name:</span><input type="text" id="username"> </p> <p> <span>Gender:</span> <input type="radio" name="sex" value="man" id="boy">male <input type="radio" name="sex" value="woman" id="girl">female </p> </form> <script> var input_text=document.getElementById('username') var boy_radio=document.getElementById('boy') var girl_radio=document.getElementById('girl') //Get the value of the input box input_text.value //Modify the value of the input box input_text.value="123" //For radio boxes, the value of multiple boxes is fixed, boy_radio.value can only get the current value boy_radio.checked //Returns whether the current result is true. If true, it is selected girl_radio.checked=true;//assignment </script>
Submit Form
<!--Form binding submission event οnsubmit=Bind a function to submit detection, true,false Return this result to the form, using onsubmit receive --> <form action="#" method="post" onsubmit="return aaa()"> <p> <span>user name:</span><input type="text" id="username" name="username"> </p> <p> <span>password:</span><input type="password" id="input-password"> </p> <input type="hidden" id="md5-password" name="password"> <button type="submit" onclick="aaa()">Submit</button> </form> <script> function aaa(){ var uname=document.getElementById('username') var pwd=document.getElementById('input-password') var md5pwd=document.getElementById("md5-password") md5pwd.value=md5(pwd.value) //You can verify and judge the form content. true means to pass, and false prevents submission return true } </script>
10,jQuery
Get jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script scr="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script> </head> <body> <!-- Formula: $(selector).action() --> <a href="" id="test-jquery">Point me</a> <script> document.getElementById('id') //Selectors are css selectors $('#test-jquery').click(function (){ alert('hello'); }) </script> </body> </html>
selector
<script> //label document.getElementsByTagName() //id document.getElementById() //class document.getElementsByClassName() //All selectors in jQuery CSS can be used $("p").click(); $("#id1").click(); $(".class").click(); </script>
event
$(select).action()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script crossorigin="anonymous" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" src="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script> <style> #divMove{ width: 500px; height: 500px; border:1px solid #48e32c; } </style> </head> <body> <!--Get a coordinate of the mouse--> mouse:<span id="mouseMove"></span> <div id="divMove"> click </div> <script> //Respond to the event when the web page element is loaded $(function (){ $('#divMove').mousemove(function (e){ $('#mouseMove').text('x:'+e.pageX+'y:'+e.pageY) }) }); </script> </body> </html>
Operation DOM
Node text operation
<body> <ul id="test-ul"> <li class="js">javascript</li> <li name="python">python</li> </ul> <script> $('#test-ul li[name=python]').text();// Get value $('#test-ul li[name=python]').text('set value ')// Get value $('#test-ul').html();// Get value $('#test-ul'). html('<strong>123</strong>');// Get value //css operation $('#test-ul li[name=python]').css("color","red"); //The essence of text display and hiding: dispay: none $('#test-ul li[name=python]').show(); $('#test-ul li[name=python]').hide(); </script>