JavaScript is a scripting language
A qualified back-end person must be proficient in JavaScript.
Introducing JavaScript
Two methods: internal label and external import
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--script Label write JavaScript code --> <!-- External introduction --> <!-- be careful: script,Must appear in pairs --> <script src="js/style.js"> // alert('hello,world'); </script> <!-- script type="text/javascript" No need to write. The default is this type --> <script type="text/javascript"> </script> </head> <body> </body> </html>
Basic grammar
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--JavaScript Strictly case sensitive--> <script> //1. Define variable type variable name = variable value var num = 1; var name = "hzx"; var flag = false; if(flag){ alert("true"); }else if(flag==false){ alert("false"); }else{ alert("123"); } //console.log() prints variables on the browser console </script> </head> <body> </body> </html>
data type
Values, text, graphics, audio, video
variable
Defining variables should not start with numbers, which is very similar to Java
number
js does not distinguish between decimals and integers, but only a Number
123 / / integer 123
123.1 / / floating point number 123.1
1.123e3 // Scientific counting method
-99 // negative
NaN // not a number
Infinity / / Infinity
character string
'abc' "abc"
Boolean value
true false
Logical operation
&& Both are true The result is true || One is true The result is true ! True or false False is true
Comparison operator (important)
= Assignment symbol == Equal to (if the type is different and the value is the same, it will also be judged as true) === Absolutely equal to (same type) Same value The result is true)
This is a JS defect. Insist not to use = =
Notice:
- Nan = = = Nan 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 operation, which has accuracy problems.
Math.abs(1/3-(1-2/3))<0.00000000001
null and undefined
- Null null
- undefined does not exist
array
JS does not require a series of objects of the same type
//To ensure the readability of the code, try to use [] var arr = [1,2,3,null,true,"123","abc"]; new Array(1,2,3,null,true,"123","abc");
Take the array subscript: if it is out of bounds, it will display undefined
object
Objects are braces and arrays are brackets
Each attribute is separated by commas, and the last attribute is not required
var person = { name: "hzx", age: 18, tags: ['java','js','...'] }
Get the value of the object
person.name; person.age; person.tags;
Strict inspection mode
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title>. <!-- Premise: IEDA Setting support required ES6 grammar 'user strict'Will be useful 'user strict'; Strict inspection mode and Prevention JavaScript Some problems caused by the randomness of 'user strict';Must be written in JavaScript First line of Local variables are recommended let definition --> <script> 'user strict'; //global variable i = 1; //Local variables in ES6 are defined with let let a = 1; </script> </head> <body> </body> </html>
Data type (details)
character string
1. Normal strings are wrapped in single quotation marks or double quotation marks
2. Note escape characters\
\' Single quotation mark \n Line feed \u4e2d \u#### Unicode character \x41 Ascii character
3. Multi line string writing can be realized in JavaScript es6
//tab under esc` var msg = ` hello world `;
4. Template string
let name = 'hzx'; let age = 18; var msg = `hello,world ${name} ${age}`; console.log(msg);
5. String length
var student = "student"; console.log(student.length); //String length student.length
6. String variability (immutable)
7. Case conversion
//Note that this is a method, not an attribute student.toUpperCase() //Convert to uppercase student.toLowerCase() //Convert to lowercase
8. Gets the specified subscript
9. substring interception (similar to Java)
[)Baotou not Baowei student.substring(1) //Intercept from the first string to the last string student.substring(1,3) //[1,3)
array
Array can contain any data type
var arr = [1,2,3,4,5,6]; //Value and assignment by subscript new Array(1,2,3,null,true,"123","abc");
1. Length
arr.length
Note: the array size will change if arr.length is assigned a value. If the value is too small, the element will be lost
2. indexOf gets the subscript index through the element
The string "1" is different from the number 1
3. slice() intercepts part of the Array and returns a new Array, similar to substring in String
4,push(),pop() tail
push: Push element to tail pop: Pop up an element at the end
5,unshift(),shift() head
unshift: Press element into head shift: Pop up an element in the header
6. sort ()
7. Element reverse ()
8. concat() splice
Note: concat() does not modify the array, but returns a new array
9. Connector join ()
Print a tiled array, concatenated with a specific string
10. Multidimensional array
Array: store data (you can use your own methods to save and retrieve data)
object
Several key value pairs
var Object name = { Attribute name: attribute value, Attribute name: attribute value, Attribute name: attribute value, Attribute name: attribute value } //Define a person object with its own properties var person = { name:"hzx", age:18, score:100 }
For the object in Js, {...} represents an object. The key value pair describes the attribute XXXX: XXXX. Multiple attributes are separated by commas, and the last attribute is not comma
All keys in JavaScript are strings, and values are arbitrary objects
1. Object assignment
2. If you use a non-existent object attribute, no error will be reported
3. Dynamically delete attributes, and delete the attributes of the object through delete
4. Dynamic addition
5. Judge whether the attribute value exists in the object! XXX in XXX For example, the toString method inherits the parent class
6. Determine whether a property is a hasOwnProperty() owned by the object itself Inheritance does not count
Process control
if judgment
let age = 3; if(age>3){ alert("hhh"); }else{ alert("kuwa"); }
while loop to avoid dead loop
let age = 3; while(age<100){ age++; console.log(age); }
for loop
for(let i = 0;i<100;i++){ console.log(i); }
forEach loop
let age = [1,2,3,4,5,6]; //function age.forEach(function (value){ console.log(value); })
for...in (array subscript)
let age = [1,2,3,4,5,6]; //function /** * for(Type Str: el){} */ //Under for(var index in age), num is the index of the age array for(var num in age){ console.log(age[num]); }
for...of (array value)
var arr = [3,4,5]; for(var x of arr){ console.log(x); }
Map and Set
New features of ES6
Map:
//ES6 //Suppose you want to count students' grades and students' names // var names = ["tom","jack","hhh"]; // var scores = [100,90,80]; var map = new Map([["tom",100],["jack",90],["hahaha",80]]); var name = map.get("tom"); //Get value through key map.set("admin",123456); //Add an element map.selete("tom"); //Delete an element console.log(name);
Set: unordered and non duplicate sets
var set = new Set([1,1,11,3]); //set can be de duplicated set.add(2); //add to set.delete(11); //delete set.has(3); //Include an element
iterator
Traversal map
var map = new Map([["tom",100],["jack",90],["hhh",80]]); for(var x of map){ console.log(x); }
Traversal set
var set = new Set(5,6,7); for(var x of set){ console.log(x); }
function
Define function
Definition method I
Absolute value function
function abs(x){ if(x>=0){ return x; }else{ return -x; } }
Once executed, return represents the end of the function and returns the result
If return is not executed, the result will also be returned after the function is executed. The result is undefined
Definition mode 2
var abs = function(x){ if(x>=0){ return x; }else{ return -x; } }
Function (x) {} This is an anonymous function, but the result can be assigned to abs, and the function can be called through abs.
Mode 1 and mode 2 are equivalent
Call function
Parameter problem: JavaScript can pass any parameter or not
Is there a problem with parameters? If there are no parameters, how to avoid them?
var abs = function(x){ //Manually throw an exception to judge if(typeof x!== 'number'){ throw 'Not a Numbre'; } if(x>=0){ return x; }else{ return -x; } }
arguments
arguments is a JS free keyword
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; } }
Problem: arguments contains all parameters. If you want to use extra parameters for additional operations, you need to exclude the existing parameters
rest
Previously:
if(arguments.length>2){ for(var i =0;i<arguments.length;i++){ //.... } }
ES6 introduces a new feature to obtain parameters other than defined parameters
Now?
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 must be identified with
Scope of variable
In JavaScript, variables defined by var are actually scoped
If it is declared in the function body, it cannot be used outside the function (closures can be used if you want to implement it)
function hzx(){ var x = 1; x = x + 1; } x = x + 1; //Uncaught ReferenceError: x is not defined
If two functions use the same variable name, they do not conflict with each other as long as they are inside the function
function hzx(){ var x = 1; x = x + 1; } function hzx1(){ var x = 1; x = x + 1; }
Internal functions can access members of external functions, and vice versa
function hzx(){ var x = 1; //Internal functions can access members of external functions, and vice versa function hzx1(){ var y = x + 1; } var z = y + 1; //1 Uncaught ReferenceError: y is not defined }
Suppose that the internal function variable and the external function variable have the same name
function hzx(){ var x = 1; //Internal functions can access members of external functions, and vice versa function hzx1(){ var x = 'A'; console.log("inner=>"+x); } console.log("outer=>"+x); hzx1(); } hzx();
Suppose that in JavaScript, the function search variable starts from its own function and searches from inside to outside. If there is an external function variable with the same name, the internal function will shield the variables of the external function.
Promote the scope of the variable
function hzx(){ var x = "x" + y; console.log(x); var y = "y"; }
Result: xundefined
Note: JS execution engine automatically promotes the declaration of Y, but does not promote the assignment of variable y; Equivalent to the following code
function hzx(){ var y; var x = "x" + y; console.log(x); y = "y"; }
This is a feature that existed at the beginning of the establishment of JavaScript. Develop norms: all variable definitions are placed at the head of the function. Don't put them randomly to facilitate code maintenance;
Global function
//global variable var x = 1; function f(){ console.log(x); } f(); console.log(x);
Global object window
var x = 1; alert(x); alert(window.x);// By default, all global variables are automatically bound under the window object
The alert() function itself is also a window variable
var x = 1; 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 global scope. If any variable (function can also be regarded as a variable) is not found within the scope of the function, it will look outward. If it is not found in the global scope, an error "ReferenceError" will be reported“
standard
Because all our global variables will be bound to our window. If different js files use the same global variables, there will be conflicts ~ how to reduce conflicts?
//Unique global variable var hzx = {}; //Define global variables hzx.name = "hzx"; hzx.add = function (a,b){ return a + b ; }
Put all your code into the unique space name defined by yourself to reduce the problem of global naming conflict
Local scope let
function aaa(){ for(var i = 0 ; i < 100 ; i++){ console.log(i); } console.log(i+1); // Problem: i out of this scope can still be used }
ES6 let keyword to resolve local scope conflicts
function aaa(){ for(let i = 0 ; i < 100 ; i++){ console.log(i); } console.log(i+1); // Uncaught ReferenceError: i is not defined }
It is recommended to use let to define variables with local scope;
Constant const
Before ES6, only variables named in all uppercase letters were constants; it is not recommended to modify such values
var PI = '3.14'; console.log(PI); PI = '3.1415926';// The value of PI can be changed console.log(PI);
The constant keyword const is introduced in ES6
const PI = '3.14'; // read-only variable console.log(PI); PI = '3.1415926'; // Uncaught TypeError: Assignment to constant variable. console.log(PI);
method
Definition method
The method is to put the function in the object. The object has only two things, attributes and methods
var hzx = { name: 'hzx', birth: 1999, // method age: function (){ // This year - year of birth var now = new Date().getFullYear(); return now - this.birth; } } //attribute hzx.name //Method, be sure to bring () hzx.age()
What does this. Stand for? Take apart the code above
function getAge(){ // This year - year of birth var now = new Date().getFullYear(); return now - this.birth; var hzx = { name: 'hzx', birth: 1999, // method age: getAge } } //hzx.age() ok //getAge() NaN
this cannot be pointed to. It points to the object that calls it by default
apply
this point can be controlled in js
function getAge() { var now = new Date().getFullYear(); return now - this.birth; }; var hzx = { name: 'hzx', birth: 1999, age: getAge }; getAge.apply(hzx,[]);//this points to hzx. The parameter is null
Internal object
Standard object
Date
Basic use
var now = new Date(); // Thu Oct 21 2021 17:01:59 GMT+0800 (China standard time) console.log(now); now.getFullYear(); // year now.getMonth(); // month now.getDate(); // day now.getDay(); // What day is today? now.getHours(); // Time now.getMinutes(); // branch now.getSeconds(); // second now.getTime(); // Globally harmonized timestamp
transformation
Json
In JavaScript, everything is an object, and any type supported by js can be represented by json;
Format:
- All objects use {}
- Arrays all use []
- All key value pairs use key: value
Conversion of JSON string and JS object
var hzx = { name: "hzx", age: 18 } console.log(hzx); //Object to json string var jsonhzx = JSON.stringify(hzx); console.log(jsonhzx); //Convert json string to object var obj = JSON.parse(jsonhzx); console.log(obj);
object-oriented programming
JavaScript object-oriented is different from Java object-oriented
- Classes: Templates
- Objects: concrete instances
Prototype:
class inheritance
class keyword, introduced in ES6
1. Define a class, property, method
// Define a student class class Student{ constructor(name) { this.name = name; } hello(){ alert("hello"); } } var xiaoming = new Student("xiaoming"); var xiaohong = new Student("xiaohong"); xiaoming.hello();
2. Inherit
<script> //After ES6 // Define a student class class Student{ constructor(name) { this.name = name; } hello(){ alert("hello"); } } class XiaoStudent extends Student{ constructor(name,grade) { super(name); this.grade = grade; } myGrade(){ alert("I'm a pupil") } } var xiaoming = new Student("xiaoming"); var xiaohong = new XiaoStudent("xiaohong",1); </script>
Essence: viewing object prototypes
Prototype chain
Operation BOM object (key)
The relationship between JavaScript and browsers?
JavaScript was born to run in browsers
BOM: Browser Object Models
- IE
- Chrome
- Safari
- FireFox
- Opera
Above is the kernel
Third party
- QQ browser
- 360 browser
window
Window stands for browser window
Navigator
Navigator, which encapsulates the information of the browser
Most of the time, we won't use the navigator object because it will be artificially modified
These attributes are not recommended for judging and writing code
screen
Represents the screen size
location (important)
location represents the URL information of the current page
document
Document represents the current page, HTML DOM document tree
Get the specific document tree node
<dl id="app"> <dt>java</dt> <dd>javase</dd> <dd>javaee</dd> </dl> <script> var l = document.getElementById('app'); </script>
document can get cookie s
document.cookie
Principle of hijacking cookie s
The server can set a cookie: httpOnly to ensure security
history
History represents the history of the browser
history.forward() //forward history.back() //back off
Manipulating DOM objects (focus)
DOM: Document Object Model
core
A web browser is a DOM tree structure
- Update: updating DOM nodes
- Traversing DOM nodes: get DOM nodes
- Delete: deletes a DOM node
- Add: adds a new node
To manipulate a DOM node, you must first obtain it
Get DOM node:
//Corresponding CSS selector var h1 = document.getElementsByTagName("h1"); var p1 = document.getElementById("p1"); var p2 = document.getElementsByClassName("p2"); var father = document.getElementById("father"); var childerns = father.children; //Gets all child nodes under the parent node father.firstChild; father.lastChild;
Update node
<div id="id1"> </div> <script> var id1 = document.getElementById("id1"); </script>
Operation text
- id1.innerText='456 'modify the value of the text
- Id1. InnerHTML = '< strong > 123 < / strong >' you can parse HTML text tags
Operation CSS
Delete node
<div id="father"> <h1>Title 1</h1> <p id="p1">p1</p> <p class="p2">p2</p> </div>
Steps to delete a node: first obtain the parent node, and then delete yourself through the parent node
var self = document.getElementById("p1"); var father = self.parentElement; father.removeChild(self);
Delete child nodes from parent nodes
Note: when deleting multiple nodes, children will change
Insert node
Get a DOM node. Assuming that the DOM node is empty, add an element through innerHTML. If an element already exists in this node, you can't do so
Add:
<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>
effect:
Create a new label to insert:
//Create a new node through JS var newp = document.createElement('p');// Create a p label newp.id = 'newp'; newp.innerText = 'hello hzx'; list.appendChild(newp); //Create a label node (any value can be set through this property) var myScript = document.createElement('script'); myScript.setAttribute('type','text/javascript');
insert
var ee = document.getElementById('ee'); var js = document.getElementById('js'); var list = document.getElementById('list'); // Insert before (new node, target node) list.insertBefore(js,ee);
Action form (validation)
Form: form DOM tree
- Text box text
- Drop down box select
- Radio radio
- Checkbox checkbox
- Hidden domain hidden
- Password box password
- .......
Purpose of the form: to submit information
Get information to submit
<form action="post"> <p> <span>user name:</span><input type="text" id="username"> </p> <!--The value of the multi selection box is defined value --> <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, multiple boxes, etc., the fixed value boy_radio.value can only get the current value boy_radio.checked; // Check whether the result is true. If it is true, it is selected girl_radio.checked = true;// assignment </script>
Submit form MD5 encryption password form optimization
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- MD5 Tool class --> <script src="https://cdn.bootcss.com/blueimp-md5/2.10.0/js/md5.min.js"></script> </head> <body> <!-- Form binding submission time onsubmit= Bind a function to submit detection ture false Return this result to the form for use 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="password" name="password"> </p> <input type="hidden" id="md5-password" name="password"> <!-- Binding event onclick Be clicked --> <button type="submit" onclick="aaa()">Submit</button> </form> <script> function aaa(){ var uname = document.getElementById('username'); var pwd = document.getElementById('password'); var md5pwd = document.getElementById('md5-password'); //MD5 algorithm md5pwd.value = md5(pwd.value); // You can verify and judge that the form content is false, the submission fails, and the true submission succeeds return false; } </script> </body> </html>
JQuery
JavaScript
There are a lot of JavaScript functions in the jQuery library
Get JQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--on-line CDN introduce JQuery--> <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script> </head> <body> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.js"></script>--> <script src="lib/jquery-3.6.0.js"></script> </head> <body> <!-- JQuery Use formula: $(selector).action() --> <a href="" id="test-jquery">Point me</a> <script> document.getElementById('id'); // Selectors are CSS selectors $('#test-jquery').click(function (){ alert('123'); }) </script> </body> </html>
selector
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> //Few native js selectors //label document.getElementsByTagName(); //id document.getElementById(); //class document.getElementsByClassName(); //JQuery selectors can be used in css $('p').click(); //tag chooser $('#id').click(); //id selector $('.class').click(); //class selector </script> </body> </html>
Document tool station: JQuery API Chinese documentation | jQuery API Chinese online manual | jQuery API download | jquery api chm
JQuery event
Mouse events, keyboard events, other events
Formula: $(selector).action()
//Mouse event <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="lib/jquery-3.6.0.js"></script> <style> #divMove{ width: 500px; height: 500px; border: 1px solid red; } </style> </head> <body> <!--Gets the current coordinates of the mouse--> mouse: <span id="mouseMove"></span> <div id="divMove"> Try moving the mouse here </div> <script> // When the web page element is loaded, respond to the event $(function (){ $('#divMove').mousemove(function (e){ $('#mouseMove').text('x:'+e.pageX+'y:'+e.pageY); }); }); </script> </body> </html>
Operation DOM
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="lib/jquery-3.6.0.js"></script> </head> <body> <ul id="test-ul"> <li class="js">JavaScript</li> <li name="python">python</li> </ul> <script> $('test-ul li[name=python]').text(); $('test-ul').html(); </script> </body> </html>
Node text operation:
$('#Test UL (Li [name = Python] '). Text(); / / get the value $('#Test UL Li [name = Python] '. Text ('set value'); / / set value $('#Test UL '). Html(); / / get the value $('#Test UL '). HTML (' < strong > 123 < / strong > '); / / set the value
CSS actions:
$('#test-ul li[name=python]').css({"color":"red"});
Display and hiding of elements: essential display: none;
$('#test-ul li[name=python]').show(); $('#test-ul li[name=python]').hide();
study
- Consolidate JS (see JQuery source code and game source code)
- Consolidate HTML and CSS (pick website)
Learning Java - Crazy God