03_ 01_ Detailed explanation of front-end JavaScript

JavaScript details - Lao sun

Course objectives:

  1. JavaScript introduction
  2. Combination of HTML and JavaScript
  3. Use of JavaScript
  4. DOM operation
  5. BOM operation

1. Introduction to JavaScript

  • Although java is used as the prefix, the relationship between java and javascript is like the relationship between wife and wife cake. There is no relationship of a dime!
  • Netscape in Netscape 2 0 first introduced JavaScript
  • The formal name of JavaScript is "ECMAScript". This standard is developed and maintained by ECMA organization, abbreviated as "js"
  • JavaScript is a web page programming technology used to add interactive behavior to HTML pages
  • JavaScript is an object-based and event driven explanatory scripting language, which is directly embedded in HTML pages, interpreted and executed by browsers without precompiling.

1.1 js features

  • You can use any text editing tool to write the program and only need a browser to execute the program (you will learn later that you can run without a browser)
  • Explain and execute: execute line by line without compiling in advance
  • Object based: built in a large number of ready-made objects
  • Suitable:
    • Client data calculation
    • Client form validity verification
    • Trigger of browser events
    • Web page special display effect production

1.2 js composition

  • ECMAScript: defines a series of standards such as core syntax, keywords, operators, data types, etc
  • DOM: document object model, which treats all nodes of an html page as one object. Manage each node more hierarchically.
  • BOM: browser object model, which is used to access and operate the browser window. Using BOM, developers can move the window, change the text in the status bar, and perform other actions that are not directly related to the page content. What makes BOM unique and often suspicious is that it is only a part of JavaScript without any relevant standards.
    • A new browser window pops up
    • Move, close, and resize browser windows
    • Locate object that provides Web browser details
    • A screen object that provides user screen resolution details
    • Support for cookie s
    • IE extends BOM and adds ActiveXObject class. ActiveX objects can be instantiated through JavaScript to realize ajax local refresh technology

2. Combination of HTML and javaScript

Three ways to use js

2.1. Inline script

  1. Click the button (trigger)
  2. Pop up frame (specific operation)
<button onclick="alert('Bullet frame test')">Click on me</button>

2.2. Internal script

  1. use
  2. The standard is to write between head and body (neck position), but in fact, it can be written inside the html file, no matter where < html > is outside and < p > < / P > is inside.
<body>
	<script> alert("Spring frame"); </script> 
</body>

2.3. External script

  1. Create a directory js under the project root directory
  2. Create a file in the JS directory with the suffix js
  3. In an html page, use
<script src="js/xx.js"></script>

The priority of the above three ways of using scripts is who is on the and who executes first. Because it is interpretative language.

3. Use of JavaScript

3.1 variables

  • Because js is a weakly typed language, when defining variables, all data types are var
  • Declared variable: VAR X; var x,y;
  • Value type: number
    • Do not distinguish between integer and floating-point values
    • All numbers are stored in 64 bit floating point format, similar to double format
  • string: string
    • The beginning and end are enclosed in single or double quotation marks
var aa="Welcome to\"JavaScript world"; 
  • Boolean type:
    • There are only two values: true and false, which also represent 1 and 0
    • In actual operation, true=1,false=0

3.1. 1 automatic type conversion

number + String: convert number to string 10+'a' -> 10a 
number + Boolean: true Convert to 1, false Convert to 0 true+5->6 
character string + Boolean: converts a Boolean value to a string true or false true+'a'->truea 
Boolean value + Boolean: converts a Boolean value to a numeric value of 1 or 0 true+true->2

3.1. 2 data type conversion function

  • parseInt: cast to integer
    • If it cannot be converted, NaN is returned (NaN property is a special value representing a non numeric value. This property is used to indicate that a value is not a number)
    • For example: parseInt("6.32") = 6
  • parseFloat: cast to float
    • If conversion is not possible, NaN is returned
    • For example: parseFloat("6.32") = 6.32
  • typeof: query the current type of value and return string / number / boolean / object
    • For example: typeof("test" + 3) = = "string"

3.1.3 null and undefined

  • null represents "no value" or "no object" in the program
    • You can clear the contents of a variable by assigning null to a variable
  • undefined
    • Variable declared but never assigned or object property does not exist

3.1. 4 arithmetic operation

  • Add (+), subtract (-), multiply (*), divide (/), remainder (%)
    • -It can represent a minus sign or a minus sign, such as x = -y
    • +It can represent addition and can also be used for string connection
  • Increment (+ +), decrement (–)
    • i + + is equivalent to i=i+1
    • i -- equivalent to i=i-1

3.1. 5 relational operation

  • Strict Equality:===
    • Same type
    • Same value
  • Non strict Equality:==
var a = "10"; 
var b = 10; 
if (a == b) 
	alert("equal"); 
if (a === b) 
	alert("same");

3.1. 6 logic operation
Logical non (!), logical and (& &), logical or (|)
The operands of logical operations are boolean expressions

  • I need two bowls of ramen or 10 steamed stuffed buns to be full! The problem is, I only eat two bowls of noodles. I'm full! I only eat 10 steamed stuffed buns. I'm full
  • I want to eat two bowls of ramen and 10 steamed buns to be full! The problem is, I only eat two bowls of noodles, not full! I only eat 10 steamed stuffed buns. I'm not full,

3.1. 7 control statement

if(Relational expression) { 
	// Statement block 1 
}else { 
	// Statement block 2 
}

if judgment statement

if (Expression 1) { 
	// Statement 1; 
}else if (Expression 2){ 
	// Statement 2; 
}else if (Expression 3){ 
	// Statement 3; 
} else{ 
	// Statement 4; 
}

switch judgment statement

switch (expression) { 
	case Value 1: 
		// Statement 1; 
		break; 
	case Value 2: 
		// Statement 2; 
		break; 
		default: // Statement 4; 
}

for loop statement:

for (var i=1 ; i<=5 ; i++){ 
	alert(i); 
}

while loop statement

while (condition){ 
	// Statement 1 
}

3.2 common string API

  • Length: get the length of the string (the number of characters in the string) property without parentheses
var str = "hello"; 
console.log( str.length );
  • toUpperCase/toLowerCase: case conversion
var name = "AngierSun"; 
console.log( "In words:"+name.toUpperCase() ); 
console.log( "a lowercase letter:"+name.toLowerCase() );
  • Charat (subscript): returns the character on a subscript
var str1 = "javascript Web tutorial"; 
var str2 = str1.charAt(12); // Characters on subscript 12 
console.log(str2); //teach 

var str3 = str1.charCodeAt(12); 
console.log(str3); //25945: (the number of Chinese character "Jiao" in unicode coding)
  • Indexof (character): find the first subscript of a character in a string
  • LastIndexOf (character): find the subscript of the last character in the string
var str1 = "javascript Web tutorial"; 
var str2 = str1.indexOf("a"); 
console.log(str2); // 1, subscript of the first occurrence of a character in str1 

var str3 = str1.lastIndexOf("a"); //3. Subscript of the last occurrence of a character in str1 
console.log(str3);
  • Substring (start, end): intercept a part of the string (the end is not included)
var str1 = "abcdefgh"; 
var str2 = str1.substring(2,4); 
console.log(str2); //cd, starting with 2 (included), ending with 4 (not included)
  • Replace (old, new): replaces the old character in the string with the new character
var str1 = "abcde"; 
var str2 = str1.replace("cd","XXX"); 
console.log(str2); // abXXXe, replace cd in str1 with XXX
  • Split (split node): a string is cut into N small strings, so the array type is returned
var str1 = "one,two,three,four,five"; 
var arr = str1.split(","); // str1 is divided into N parts by comma, so the returned result must be an array structure 
console.log( "Divided into:"+arr.length+"share" ); 
console.log( "The third is:" + arr[2] ); // three

3.3 array

3.3. 1 create array

var arr1 = new Array();

3.3. 2 three ways to initialize an array

// First kind 
var arr1 = new Array(); 
arr1[0] = 110; 
arr1[1] = 119; 
arr1[2] = 120; 
// Second 
var arr1 = new Array(10,"a",true); 
// Third 
var arr1 = [10,"a",true]; 
for (var i = 0; i < arr1.length; i++) { 
	console.log(arr1[i]); 
}

3.3. 3 common methods of array

  • tostring(): converts an array to a string
var arr = [1,2,3,4]; 
console.log("Type:" + typeof( arr ) ); 
var str = arr.toString(); // Convert array to string 
console.log( str +",Type:" + typeof( str ) );
  • Join: concatenate each element in the array into a new string.
var arr = [1,2,3,4]; 
var str = arr.join("-"); // Connect each element in the array with - to form a new string 
console.log( str +",Type:" + typeof( str ) );
  • Concat (new element): connect the original array to the new element, and the original array remains unchanged.
var arr = [1,2,3,4]; 
var arrnew = arr.concat(5,6); // Add new elements after the arr array to form a new array, but the original array is unchanged 
console.log( arrnew +",Type:" + typeof( arrnew ) ); 
console.log("Original array:" + arr);
  • Slice (start, end): extract a part from the array to form a new array.
    • 1,2,3,4,5 slice(2,4) results: 3,4
var arr = ['a','b','c','d','e','f','g','h']; 
var arrnew = arr.slice( 2,4 ); // Intercept in the arr array, starting from 2 (inclusive) and ending at 4 (exclusive)
console.log( arrnew ); // cd
  • reverse(): the reverse order of the array
var arr = [31,12,111,444]; 
console.log( arr.toString() ); 
arr.reverse(); // Inverts the elements in the array 
console.log( arr.toString() );
  • sort(): array sorting
    • arr.sort() character sort
var arr = [31,12,111,444]; 
arr.sort(); // Character sorting (not by literal size) 
console.log( arr );
  • arr.sort(func) numeric sort
var arr = [31,12,111,444]; 
arr.sort( laosun ); // Sort by number (according to the literal size) 
console.log( arr ); // Define sort function 

function laosun(a,b){ 
	return a-b; 
}

3.4 Math object of math

  • Math objects are used to perform mathematical tasks
  • No constructor Math()
  • Without creating, you can call all its properties and methods by directly using Math as an object
// Returns any random number between 0 and 9 
var i = Math.random() * 10; 
var j = Math.floor(i); 
console.log(j);

3.5 Number object

Number.fixed(2); Self rounding skill

var n = new Number( 12.345 ); 
var n1 = n.toFixed(2); // 12.35, fixed two decimal places, the third decimal place is rounded 
console.log( n1 ); 
var x = new Number( 12.3 ); 
var n2 = x.toFixed(2); // 12.30. Fix two decimal places. If the number of decimal places is not enough, 0 will be used to supplement 
console.log( n2 );

3.6 regular expressions

Powerful tool for performing pattern matching on strings

var reg1 = /^\d{3,6}$/; // Match 3-6 pure numbers 
var reg2 = new RegExp("^\\d{3,6}$");

// Mode 1 
var age = "18"; // Judgment: 1-3 pure digits 
var reg = /^\d{1,3}$/; // Start with / ^, write regular content in the middle, and end with $/ 
var b = reg.test(age); // Verify that the of the age variable matches reg 
if (b == true) { 
	console.log("Verification passed!"); 
} else { 
	console.log("Format error"); 
}

// Mode 2 
var name = "abc123"; // Combination of upper and lower case letters and numbers (special characters cannot appear), 5 ~ 8 digits 
var reg = new RegExp("^[a-zA-Z0-9]{5,8}$"); // Start with ^, write regular content in the middle, and end with $ 
if (reg.test(name)) { 
	console.log("Verification passed!"); 
} else { 
	console.log("Format error"); 
}

3.7 Date object

var time = new Date(); 
console.log( time ); // Tue Jul 14 2020 11:09:46 GMT+0800 (China standard time) 
var year = time.getFullYear(); // particular year 
var month = time.getMonth() + 1; //The month starts from 0 and ends in 11, so the domestic habit should be + 1 
var day = time.getDate(); // What number 
var hour = time.getHours(); // what time? 
var mm = time.getMinutes(); // minute 
var s = time.getSeconds(); //second 
var ms = time.getMilliseconds(); // Milliseconds, 1000 milliseconds = 1 second 
var timestr = year+"year"+month+"month"+day+"number "+hour+"spot"+mm+"branch"+s+"second"+ms+"millisecond"; 
console.log( timestr );

3.8 functions

  • Use the keyword function to define a function
function Function name( parameter list  ){ 
	// Function body 
	return Return value; 
}
  • The function will not be executed immediately after declaration, and will be called when we need it.
  • be careful:
    • Formal parameters: do not take data types
    • Semicolons are used to separate executable JavaScript statements. Since the function declaration is not an executable statement, it does not end with a semicolon.

3.8. 1 no return value

function qiuhe(a, b) { 
	var he = a + b; 
	console.log("Sum of two numbers:" + he);
}

qiuhe(3,4);

3.8. 2 has a return value

function qiuhe(a, b) { 
	var he = a + b; 
	return "Sum of two numbers:" + he;
}
var s = qiuhe(3,4); 
console.log( s );

3.8. 3 parameter object

Inside the function, call the properties of the parameter list

function func(a,b,c){ 
	console.log( arguments.length ); // Get the number of parameters 
	console.log( arguments[1] ); // Get parameter with subscript 1 
}

3.8. 4 constructor

Functions can also be defined through the built-in JavaScript function constructor (Function())

var myFunction = new Function("a", "b", "return a * b"); 
var x = myFunction(4, 3); 
console.log(x);

Note: the above function ends with a semicolon because it is an execution statement.

3.8. 5 anonymous function

Function without name

var fn = function(a, b) {// A function without a name should be received with a variable 
	return a * 10 + b; 
};

console.log( fn(3, 4) );

3.8. 6 global functions

  • isNaN: check whether its parameters are non numeric values
console.log( isNaN( 123 ) ); // Number, false 
console.log( isNaN( "hello" ) ); // Non numeric, true 
console.log( isNaN( 4-1 ) ); // Number, false 
console.log( isNaN( 123 ) ); // Number, false 
console.log( isNaN( -10 ) ); // Number, false 
console.log( isNaN( "123" ) ); // Number, false 
console.log( isNaN( "1a23" ) ); // Non numeric, true
  • eval: used to convert operations in strings
var str = "1+3"; 
console.log( str ); // 1 + 3, + will be recognized as a character symbol, without the function of addition 
console.log( eval( str ) ); // Make the operation symbols in the string effective
  • encodeURI and decodeURI
var name = "Pull hook net"; 
console.log( "Before transcoding:" + name ); 

name = encodeURI(name); 
console.log( "After transcoding:" + name ); 

name = decodeURI(name); 
console.log( "After decoding:" + name );

3.8. 7 closure

  1. The concept of closure: refers to a function that has access to variables in the scope of another function. Generally, one function contains another function.
  2. The function of closures: access internal variables of functions and keep functions existing in the environment all the time and will not be handled by garbage collection mechanism;
    To put it simply: declare a closed environment within the local scope of the function, which will not be detected by garbage collection. Ensure the security and uniqueness of data
    To understand closures, you must first understand what global variables are and what local variables are
	a = 10; // Global variable, which can not be used when declaring
	var function test1(){ b = 20; // Variables that do not apply to var declarations are global variables 
	var c = 30; // It is declared with var and inside the function. Such a variable is called a local variable, and the valid range can only be inside the function it declares 
	console.log(c); 
}

function test2(){ 
	console.log(c); //C is not defined 
	}

test1(); 
test2();

Requirement: how many times has the statistical method been executed

var count = 0; // Total times 
function test1(){ 
	count++; // Self increment + 1 
}
test1(); test1(); test1(); 

console.log( count );

Anyone can access count, so the count variable is not safe because it is a global variable.
How can we be safe? Declare count as a local variable

function test1(){ 
	var count = 0; //local variable 
	return count++; //Count cannot be accessed externally. You can only return the count variable and output it through return 
	}
	test1(); test1(); test1(); 
	console.log( test1() ); // Every time a method is called, the first step is to restore the variable to 0

The result is always 0, because every time test1() is called, the first sentence of the method body is to restore, regardless of the previous value.
It's a whim. If another function is nested in test1() function, js supports function nesting

function test1(){ 
	var count = 0; //local variable 
	function jia(){ 
		return count++; 
	}
	jia(); 
	return count; 
} 
test1(); test1(); test1(); 
console.log( test1() ); // Every time a method is called, the first step is to restore the variable to 0

If only jia() in test1() is called at a time. ok, closures help you solve this problem!

function test1(){ 
	var count = 0; //local variable 
	function jia(){ 
		return count+=1; 
	}
	return jia; 
}
var fn = test1(); // fn => function jia(){return count+=1; } 
fn(); fn(); 
console.log( fn() ); // Every time a method is called, the first step is to restore the variable to 0

Closure is a mechanism to protect private variables. It forms a private scope during function execution to protect the private variables from external interference.
Intuitively, it is to form a stack environment that is not destroyed.

  • Advantages of closures: it is convenient to call the local variables declared in the context, and the logic is tight. You can create another function in a function to avoid the problem of parameter passing
  • Disadvantages of closures: because closures are used, functions can not be destroyed after execution and remain in memory. If closures are used heavily, memory leakage will occur and memory consumption will be great

3.9 bullet frame output

  • Ordinary pop-up alert("hello, pull hook");
  • Console log output console Log ("Google browser press F12 to enter the console");
  • Page output document write(“

    I love you China

    ”); take

    Element output to

  • Confirmation box confirm("are you sure to delete?");
var b = confirm("Are you sure to delete?"); 
if(b){
	document.write( "<h1>Delete succeeded!</h1>" ); 
}else{
	document.write( "<h1>You canceled the operation</h1>" ); 
}

Input box prompt("please enter name:");

var name = prompt("Please enter your name:"); 
document.write( "<h1>name:"+name+"!</h1>" );

4.DOM operation

  • In an html page, many tags will be used to plan and make the page.
  • Each tag has its meaning. If we want to dynamically modify the value of a tag. Then we need to find this tag element in the page
  • How to find this element is a difficult problem. Engineers of W3C organization suddenly saw a big tree. What should I do if I want to find a leaf?
  • "Follow the vine and touch the melon". The main trunk has branches, and each branch has many small branches. As long as the structure of this branch is sorted out clearly, it is not difficult for any leaf
  • Inspired by leaves and trees, engineers held a meeting to discuss the theory "document object model",
  • The document object model regards all label elements in the page as an object (a leaf), and the main trunk is defined as the root node (root element). All labels extend from the root element. It is no longer difficult to find a label by finding out the structure
    • In the node tree, the top node is the root node
    • Every node has a parent node (except the root node)
    • Any node can have any number of child nodes
    • Siblings are nodes that have the same parent node
<html>
	<head>
		<meta charset="utf-8"> 
		<title>DOM course</title> 
	</head> 
<body>
	<h1>Section I: HTML DOM</h1> 
	<p>Hello world!</p> 
</body> 
</html>

From the HTML above:

  • <html>Node has no parent node; It is the root node
  • The parent nodes of < head > and are nodes
  • Text node "Hello world!" The parent node of is the < p > node
    And:
  • <html>The node has two child nodes: < head > and < body >
  • The < head > node has two child nodes: < meta > and < title > nodes
  • The < title > node also has a child node: the text node "DOM tutorial" < H1 > and < p > nodes are sibling nodes and child nodes of < body >
    And:
  • The < head > element is the first child node of the < HTML > element
  • <body>The element is the last child node of the < HTML > element
  • <h1>The element is the first child node of the < body > element
  • <p>The element is the last child node of the < body > element
    js provides us with many methods to find an element node on the page

4.1 DOM access

  • getElementById: get the element node object through the id attribute
    • Case: prevent form submission when the account number is empty
<body>
	<form action="xxx" onsubmit="return login()"> 
		<p>Account number:<input id="username"/></p> 
		<p>Telephone:<input id="phone"/></p> 
		<p><button>Sign in</button></p> 
	</form>
	<script> function login() { 
		var name = document.getElementById("username").value ; 
		if(name == ""){ 
		alert("Account number cannot be empty!"); 
		return false; // Block form submission 
		}return true; // Release and let the form submit 
	} 
	</script> 
</body>
  • getElementsByName: get the element node object set through the name attribute
Case: shopping cart select all effect
<body>
    <h2>My shopping cart</h2>
    <table border="1" cellspacing="0">
        <tr>
            <td><input type="checkbox" onchange="quan(this)" />
                Select all</td>
            <td>name</td>
            <td>Unit Price</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="one" />1</td>
            <td>Functional drinks-scream</td>
            <td>4.0</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="one" />2</td>
            <td>Ham sausage</td>
            <td>2.0</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="one" />3</td>
            <td>steamed stuffed bun</td>
            <td>1.5</td>
        </tr>
    </table>
    <p><button>place order</button> </p>
    <script> function quan(all) {
            var arr = document.getElementsByName("one");
            for (var i = 0; i < arr.length; i++) {
                arr[i].checked = all.checked;
                // Assign the status of all check boxes to each check box 
            }
        }</script>
</body>
  • getElementsByTagName: get the element node object set by tag name
Case: table interlaced color change
<body>
    <table border="1" cellspacing="0">
        <tr>
            <td><input type="checkbox" onchange="quan(this)" /> Select all</td>
            <td>name</td>
            <td>Unit Price</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="one" />1</td>
            <td>Functional drinks-scream</td>
            <td>4.0</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="one" />2</td>
            <td>Ham sausage</td>
            <td>2.0</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="one" />3</td>
            <td>steamed stuffed bun</td>
            <td>1.5</td>
    </table>
    <script> var rows = document.getElementsByTagName("tr"); //Get a collection of element objects by tag name 
        for (var i = 0; i < rows.length; i++) {
            if (i % 2 == 1) {
                // Odd number 
                rows[i].style.backgroundColor = "pink";
            }
        }</script>
</body>

4.2 DOM modification

  • Modifying the HTML DOM means many different things:
    • Change HTML content
    • Change CSS Style
    • Change HTML attributes
    • Create a new HTML element
    • Delete existing HTML elements
    • Change event (handler)
  1. Change the HTML content of a < H2 > element:
<body><button onclick="test()">Let me try</button>
    <script> function test() { document.getElementById("hello").innerHTML = "Come on, have a drink~!"; }</script>
    <h2 id="hello">Hello!</h2>
</body>
  1. Change the HTML style of a < H2 >
<body>
	<button onclick="chou()">What are you looking at</button>
	    <script> function chou() { 
	        document.getElementById("hello").style.color = "red"; document.getElementById("hello").style.fontFamily = "Hua Wen Caiyun"; 
	        }</script>
	    <h2 id="hello">Hello!</h2>
</body>

4.2. 1 add node

  • Click the button to create a picture in the page
<body>
    <button onclick="add()">add to</button>
    <div></div>
    
    <script> function add() {
            var img = document.createElement("img"); // <img> 
            img.setAttribute("src", "../lagou-html/img/cat.gif"); // <img src="../lagou-html/img/cat.gif"> 
            img.setAttribute("title", "little cat"); // < img SRC = ".. / Lagou - HTML / img / cat. GIF" title = "Kitty" > 
            img.setAttribute("id", "cat"); // < img SRC = ".. / Lagou - HTML / img / cat. GIF" title = "Kitty" id = "cat" > 
            var divs = document.getElementsByTagName("div");
            divs[0].appendChild(img);
        }</script>
</body>

4.2. 2 delete node

  • Click the button to delete the image just created above from the page
<body>
    <button onclick="add()">add to</button> 
    <button onclick="del()">delete</button>
    <div> </div>
    <script> function add() { 
        . . . Slightly... 
    } function del() {
            var img = document.getElementById("cat");
             img.parentNode.removeChild(img); // You must pass the parent node to delete a child node
        }</script>
</body>

4.2. 3 replacement node

  • Click the button to replace the picture just created above with another one
<body><button onclick="add()">add to</button> <button onclick="del()">delete</button> <button onclick="rep()">replace
    </button>
    <div> </div>
    <script> function add() { . . . Slightly... }
        function del() { . . . Slightly... } function rep() {
            var imgold = document.getElementById("cat");
            // By modifying the attributes of the element, you can make a new replacement 
            // img.setAttribute("src","../lagou-html/img/2.jpg"); 
            var imgnew = document.createElement("img");
            imgnew.setAttribute("src", "../lagou-html/img/1.jpg");
            imgold.parentNode.replaceChild(imgnew, imgold);
        }</script>
</body>

4.3 events

js captures the feedback made by an action
Examples of HTML events:

  • When the user clicks the mouse
  • When the web page is loaded
  • When the picture is loaded
  • When the mouse moves over an element
  • When the input field is changed
  • When an HTML form is submitted
  • When the user triggers the key

4.3. 1 window events

Valid only in body and frameset elements.

  • onload executes the script when the document is loaded
<body onload="test()">
    <script> function test() { document.write("Ha ha ha ha"); }</script>
</body>

4.3. 2 form element events

Valid only in form elements.

  • onblur executes the script when the element loses focus
  • onfocus executes the script when the element gains focus
<body>
    <script> function a() { console.log("Get focus==Activated"); } function b() { console.log("Lose focus"); }</script>
    <form action="">
        <p>Account number:<input onfocus="a()" onblur="b()" /></p>
        <p>password:<input /></p>
    </form>
</body>

4.3. 3 mouse events

  • onclick executes the script when the mouse is clicked
  • Ondbllick executes the script when the mouse is double clicked
  • onmouseout executes a script when the mouse pointer moves out of an element
  • onmouseover executes the script when the mouse pointer hovers over an element
<style>
    img {
        width: 30%;
        border: 5px solid white;
    }
</style>

<body><img src="img/logo.png" onmouseover="shang(this)" onmouseout="xia(this)" onclick="dan()"><img src="img/logo.png"
        onmouseover="shang(this)" onmouseout="xia(this)" ondblclick="shuang()"><img src="img/logo.png"
        onmouseover="shang(this)" onmouseout="xia(this)">
    <script>function dan() {
            alert("Click");
        }

        function shuang() {
            alert("Read fast twice in a row");
        }

        function shang(img) {
            img.style.border = "5px solid red";
        }

        function xia(img) {
            img.style.border = "5px solid white";
        }

    </script>
</body>

4.3. 4 keyboard events

  • onkeydown press down
  • onkeyup pops up
<script> window.onkeydown = function () {
        // Event: event source (key) 
        // console.log("key code:" + event.keyCode "); 
        if (event.keyCode == "13") {
            // enter key 
            alert("Login succeeded!");
        }
    }

    window.onkeyup = function () {
        console.log(event.keyCode); // Pressing and holding the button will not trigger. When you let go, the key rebounds and is triggered 
    }
</script>

4.3. 5 event bubbling

  • Create two div's, one larger and one smaller
<style>
    #father {
        width: 200px;
        height: 200px;
        background: black;
        padding: 10px;
    }

    #child {
        width: 100px;
        height: 100px;
        background: greenyellow;
    }
</style>

<body>
    <div id="father">
        <div id="child"></div>
    </div>
    <script> // The code is not important. The important thing is to know that this event occurs. It is a normal phenomenon 
        document.getElementById("father").addEventListener("click", function () {
                alert("The event of the parent element is triggered:" + this.id);
            });
        document.getElementById("child").addEventListener("click", function (e) {
            e.stopPropagation() //Cancel the bubbling mechanism of the event 
            alert("The event of the child element is triggered:" + this.id);
        });</script>
</body>

First son, then father. The triggering sequence of events is from inside to outside, which is event bubbling;

4.3. 6 event capture

  • Or did you just create two div s, one larger and the other smaller
<style>
    #father {
        width: 200px;
        height: 200px;
        background: black;
        padding: 10px;
    }

    #child {
        width: 100px;
        height: 100px;
        background: greenyellow;
    }
</style>

<body>
    <div id="father">
        <div id="child"></div>
    </div>
    <script>
        document.getElementById("father").addEventListener("click", function () {
            alert("Parent:" + this.id);
        },
            true);
        document.getElementById("child").addEventListener("click", function () {
            alert("Children:" + this.id);
        }, true);
    </script>
</body>

Father before son. The event triggering sequence is changed to from outside to inside, which is event capture;

4.4 object oriented OOP

  • Create generic objects using Object
    <script>
        var user = new Object(); user.name = "Lv Bu"; user.age = 21; user.say = function () {
            console.log("Hello, my name is:" + this.name + ",I this year" + this.age + "Years old!");
        }
        user.say();
        var dog = new Object();
        dog.nickname = "Excrement and urine"; 
        dog.wang = function () { 
            console.log("I'm hungry. I'm going to tear down my house!"); 
        }
        dog.wang();
    </script>
  • Use constructor
    <script>
        function userinfo(name, age) {
            this.name = name; this.age = age; this.say = function () {
                console.log("Hello, my name is:" + this.name + ",I this year" + this.age + "Years old!");
            }
        }
        var user = new userinfo("James", 35);
        user.say();
    </script>
  • Use direct quantity
    <script>
        var user = {
            username: "Sun WuKong", age: 527, say: function () {
                console.log("Hello, my name is:" + this.username + ",I this year" + this.age + "Years old!");
            }
        };
        user.say();
    </script>

4.5 JSON

  • It's very difficult for people to analyze the data transmitted back and forth on the Internet without a unified format (everyone's coding is different)
  • JSON(JavaScript Object Notation) is a lightweight data exchange format.
  • It is easy for people to read and write, and it is also easy for machines to parse and generate
    {
    Attribute 1: value 1,
    Attribute 2: value 2,
    . . . .
    }
    <script>
        var json1 = { username: "Lv Bu", age: 31 };
        console.log("full name:" + json1.username + ",Age:" + json1.age + "year");
        // json array 
        var josnarr = [{ name: "army officer's hat ornaments", age: 18 }, { name: "Little Joe", age: 17 }];
        console.log("army officer's hat ornaments" + josnarr[0].age + "Years old");
        console.log("Little Joe" + josnarr[1].age + "Years old"); // Complex json objects 
        var long = {
            name: "Zhao Yun",
            sex: "male",
            hobby: ["Magnolia white dragon foal", "Gentian bright silver gun", "Green Sword"]
        };
        onsole.log(long.name + "Main attack weapon:" + long.hobby[1]);
    </script>

5. BOM operation

This is how javascript operates the browser

5.1 window object

    <button onclick="kai()">Quick entry</button>
    <script> function kai() {
            window.open("http://lagou. Com "," dragnet "," width=500,height=300,left=400"); // window.open("http://lagou.com "," dragnet "," fullscreen=yes "); 
            // IE takes effect
        }
    </script>

5.1.1 screen screen object

I wonder how big my computer screen is? In fact, what you get is resolution

<body>
    <button onclick="kai()">Find size</button>
</body>
<script> function kai() { 
    alert(window.screen.width + "|" + window.screen.height); }
</script>

5.1.2 location positioning

Contains information about the current URL, which is usually used for page Jump

<button onclick="test()">test</button>
<script>
    function test() {
        console.log("Of the current page URL Path address:" + location.href); 
        location.reload(); // Reload the current page (refresh)
        location.href = "http://lagou.com "; / / jump to page 
    }
</script>

5.1.3 history browser history

The history object will record the trace of the browser:

  • a.html
<a href="b.html">go b page</a>
  • b.html
<button onclick="hui()">return</button>
<script>
    function hui() { //history.go(-1); 
        //Previous page 
        history.back(); // It is equivalent to go(-1) 
    }
</script>

5.1.4 navigator navigation (understand)

window. The Navigator object contains information about the visitor's browser;

<script>
    var str = "";
    str += "<p>Browser code:" + navigator.appCodeName + "</p>";
    str += "<p>Browser name:" + navigator.appName + "</p>";
    str += "<p>Browser version:" + navigator.appVersion + "</p>";
    str += "<p>Hardware platform:" + navigator.platform + "</p>";
    str += "<p>User agent:" + navigator.userAgent + "</p>";
    str += "<p>Enable Cookies: " + navigator.cookieEnabled + "</p>";
    document.write(str);
</script>

5.1. 5 storage objects

It is very similar to our map in java. It stores data in the form of key value pairs

5.1. 5.1 local storage

This data will be deleted after closing the window or tab

  • Save data
localStorage.setItem("name","curry");
  • Extract data
localStorage.getItem("name");
  • Delete data
localStorage.removeItem("name");

Diversified operation

<script>
    // There are three ways to save data 
    localStorage["a"] = 1;
    localStorage.b = 2;
    localStorage.setItem("c", 3);
    // View data types 
    console.log(typeof localStorage["a"])
    console.log(typeof localStorage["b"])
    console.log(typeof localStorage["c"])
    // The first way to read 
    var a = localStorage.a; console.log(a);
    // The second way is to read
    var b = localStorage["b"]; console.log(b);
    // The third way to read 
    var c = localStorage.getItem("c");
    console.log(c);
</script>
5.1. 5.2 session storage

Session is to keep the browser closed.
Closing browsing is equivalent to ending a session.
Opening the browser means creating a session.

  • Save data
sessionStorage.setItem("name", "klay");
  • Extract data
var lastname = sessionStorage.getItem("name");
  • Deletes the data for the specified key
sessionStorage.removeItem("name");
  • Delete all data
sessionStorage.clear();

Case: record how many clicks of the button

<button onclick="dian()">Point me</button>
<h3 id="result"></h3>
<script> function dian() {
        if (sessionStorage.getItem("clickCount")) {
            sessionStorage.setItem("clickCount", Number(sessionStorage.getItem("clickCount")) + 1);
        } else {
            sessionStorage.setItem("clickCount", 1);
        }
        document.getElementById("result").innerHTML = "Already clicked" + sessionStorage.getItem("clickCount") + "Times!"
    }
</script>

5.2 timing operation

5.2. 1 periodic timer setInterval

setInterval(1,2): periodic trigger code exp (common)
1: Execute statement
2: Time period in milliseconds

  • Case: flashing font (1 second 1 color change)
<body>
    <h1 id="title">Dragnet: rapid entry</h1>
    <script>
        var colors = ["red", "blue", "yellow", "pink", "orange", "black"];
        var i = 0; function bian() {
            document.getElementById("title").style.color = colors[i++];
            if (i == colors.length) {
                i = 0; // Color restart 
            }
        } setInterval(bian, 100); // Execute the bian function every 0.1 seconds 
    </script>
</body>
  • Case: extended on the basis of flashing font, flashing electronic clock
<h1 id="title"></h1>
<script>
    var colors = ["red", "blue", "yellow", "pink", "orange", "black"];
    var i = 0; function bian() {
        document.getElementById("title").style.color = colors[i++];
        if (i == colors.length) {
            i = 0; // Color restart 
        }
    } function time() {
        var d = new Date();
        var str = d.getFullYear() + "year" + (d.getMonth() + 1) + "month" + d.getDate() + "number " + d.getHours() + "spot" + d.getMinutes() + "branch" + d.getSeconds() + "second"; document.getElementById("title").innerHTML = str;
    }
    setInterval(bian, 100);     // The color changing function bian is executed every 1 second 
    setInterval(time, 1000); // The time function time is executed every 1 second
</script>
</body>

5.2. 2 stop timer clearInterval

  • Case: simulation annual meeting lucky draw
<body>
    <img id="tu" src="../lagou-html/img/1.jpg" width="50%" /> <br />
    <button onclick="begin()">start</button>
    <button onclick="stop()">stop it</button>
    <script> var arr = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];
        function begin() {
            timer = setInterval(bian, 100); // var is not used, so timer is a global variable 
        } function stop() {
            clearInterval(timer);     // Stop Timer 
        } function bian() {
            var i = Math.floor(Math.random() * arr.length); // 0-4 
            document.getElementById("tu").src = "../lagou-html/img/" + arr[i];
        }</script>
</body>

5.2. 3 one time timer setTimeout

It is equivalent to the effect of delay and is executed only once

    <script>
        function bian() { document.body.style.backgroundColor = "red"; }//3 seconds later 
        setTimeout(bian, 3000);
    </script>

Keywords: Javascript Front-end Ajax

Added by Miker on Tue, 04 Jan 2022 13:00:37 +0200