Java full stack web page technology: 3.JavaScript

Chapter 1 origin of JavaScript

1.1 origin

  • N years ago

    • Dial up internet access, the network speed is very slow, the data is submitted to the server for verification, and the experience is very poor

    • Therefore, some people are thinking: can we verify these data on the browser side?

  • 1990s

    • In 1995, Brendan Eich of Netscape company first designed and implemented it on Netscape Navigator browser. Netscape originally named its scripting language LiveScript.
    • Later, Netscape cooperated with Sun. The management of Netscape wanted it to look like Java, so it was named JavaScript.
    • In 1996, Microsoft introduced its own implementation of JavaScript JScript in its latest IE3 browser, so there are two versions of JavaScript on the market. One is Netscape JavaScript and the other is Microsoft JScript. In order to ensure the consistency of JavaScript standards running on different browsers, Netscape, the creator of JavaScript, submitted JS to the international standards organization ECMA (European Computer Manufacturers Association) in November 1996, hoping that this language can become an international standard. Then ECMA issued the standard for browser scripting language, ECMAScript.
    • JavaScript is a client script language, which mainly runs in the browser. The program responsible for running JavaScript script code in the browser is called JavaScript engine.
  • Colorful now

    • Today, JavaScript is not only limited to form verification, but also contributes to many dazzling and dynamic special effects on Web pages

1.2 relationship between Java and JavaScript

java and JavaScript are two unrelated languages.

1.3 characteristics

**① Interpretive language** JavaScript is an interpretative script language. C, C + +, Java and other languages are compiled before execution. JavaScript is interpreted line by line during the operation of the program, and does not need to be compiled into machine code before execution.

**② Object oriented** JavaScript is an object-oriented scripting language. It can not only create objects, but also use existing objects.

**③ Syntax of classes C and Java** The syntax structure of as like as two peas and C, JavaScript, and for, if, while and other statements are basically the same as those of Java. The Java structure is similar to that of Java.

④ Simple. The JavaScript language uses weakly typed variable types and does not have strict requirements on the data types used. It is a scripting language based on java basic statements and control. (add: Java is a strongly typed language)

**⑤ Dynamic** The so-called dynamic nature can be temporarily understood as that all contents in language are uncertain. For example, if a variable is an integer at one moment, it may become a string at the next moment.

**⑥ Cross platform** JavaScript scripting language does not depend on the operating system (Java depends on the JVM) and only needs the support of the browser. Therefore, a JavaScript script can be brought to any machine for use after writing, provided that the browser on the machine supports JavaScript scripting language. At present, JavaScript has been supported by most browsers.

⑦ * * security** JavaScript does not allow direct access to the local hard disk.

1.4 JavaScript composition

A complete JavaScript implementation should consist of the following three parts:

  • ECMAScript: ECMAScript is a standard, which needs to be implemented by various manufacturers.

  • DOM: HTML documents are operated through DOM (document object model) in JS. As long as you understand DOM, you can operate WEB pages at will.

  • BOM: to use JavaScript in the browser, you must use BOM (browser object model). BOM provides many objects. By modifying the properties of these objects and calling their methods, it is used to control various behaviors of the browser.

1.5 experience

The corresponding code is implemented as follows:

<head>
    <!-- JavaScript The code is written in Script In label -->
    <script type="text/javascript">
        window.onload = function(){//main
        //Get #btnId corresponding element node
        var btn = document.getElementById("btnId");
        //Click response function for #btnId binding
        btn.onclick = function(){
        //A warning box pops up, displaying the string Hello
               alert("Hello");
        }
        }
    </script>
</head>
<body>
    <button id="btnId">SayHello</button>
</body>

Chapter 2 basic JavaScript syntax

JavaScript needs to be included in the < script > tag, which can appear anywhere on the page.

2.1 writing location

  • Method 1: write it into the < script > tag in HTML and declare it in the head tag or body tag.
<script type="text/javascript">
		alert("Would you like to exchange money for time?");
</script>

Note: the general declaration is in the head tag, which is a bit like the style tag.

  • Method 2: write in an external. js file. It is then introduced through the src attribute of the script tag.
    • The file path here can be relative or absolute.
<script type="text/javascript" src="script.js"></script>

Note: type attribute: the default value is text/javascript, which can be left blank.

src attribute: when you need to import an external js file, use this attribute to point to the address of the file.

Special attention: mode 1 and mode 2 should not be used at the same time. Once used at the same time, the js code in the js file in mode 2 will be executed by default.

2.2 reserved words for identifiers and keywords

2.2.1 naming rules of identifiers:

  • It consists of 26 English letters in case, 0-9_ Or $composition.
  • A number cannot begin.
  • Keywords and reserved words cannot be used, but they can be included.
  • JavaScript is strictly case sensitive.
  • The identifier cannot contain spaces.

2.2.2 keywords and reserved words

  • keyword

  • Reserved word

2.3 variables

2.3.1 data type of JavaScript

  • Basic data types (5)

    • Value type: number. For example: 1, 1.1
    • String type: string. For example: "scdsadf"
    • boolean type: boolean: only true and false
    • Null type: null
    • Undefined: only unassigned values are declared.
  • Object type:

    • Function object: function
    • Array objects: array
      • Using typeof, the result is Object
    • General Object: Object

You can use typeof (variable name) to determine the type of variable

2.3.2 special constant values in JavaScript

  • Undefined: it means undefined. Undefined type has only one value, that is, special undefined. The default value of all variables in js is undefined when they are not initialized.

    • typeof(undefined) the result is undefined.
  • Null: indicates a null value. Null type has only one value, that is, null.

    • Semantically, null represents an empty Object. Therefore, using typeof to check null will return an Object.
    • Undefined is derived from null value, so whether undefined and null are equal will return true.
  • NaN: not a number. If no result is returned when calculating a number in a mathematical operation, NaN is returned

    var a = "abc";
    var b = 12;
    var c = b * a;
    alert(c);
    
  • boolean type: can only be true or false. Other values are not supported.

    • Conversion rules between other values and boolean:

  • 0, null, undefined and "" (empty string) are considered false during operation

    <script type="text/javascript">
    // 	var i = 0;
    // 	var i = null;
    // 	var i = undefined;
    	var i = "";
    	if (i) {
    		alert("really");
    
    	} else {
    		alert("false");
    	}
    </script>
    

2.3.3 declaration of variables

  • Use var to define. For example: var num = 65; var name = "Ma Dayun";
  • Variable declaration does not need to specify the type, and all data types can be accepted.

2.3.4 assignment of variables

  • Variables can accept different types of values during assignment. For example: var x = 123; x = “atguigu.com”;
  • Variables without assignment are undefined by default
  • Use typeof (variable name) to determine the type of variable
  • Each statement in JS ends with a semicolon (;). If you do not write a semicolon, the browser will automatically add it, but it will consume some system resources.

2.4 notes

First, there are comments in js. There are two ways:

  • //Represents a single line comment
  • /** / indicates multiline comments

2.5 operators

Operator is a special symbol used to represent the operation, assignment and comparison of data.

2.5.1 arithmetic operators

2.5.2 assignment operator

  • Symbol:=
  • Extended assignment operators: + =, - =, * =, / =,%=

2.5.3 relational operators

  • <, >, <=, >=, !=, ==, === (congruent)== (incomplete)

  • Example 1:

  • Example 2:

    var i = 12;
    var j = "12";
    alert(i == j);//true.  The = = in this case is just a simple comparison of literal values
    alert(i === j);//false.  In this case, the = = = not only compares the literal value, but also compares whether the types of the two variables are consistent
    

==: is to compare whether the values of two variables are equal. For example: 12 = "12"
===: compares whether the values and data types of two variables are equal

2.5.4 logical operators

  • Logical operator, the result returns a Boolean value.

  • If the operand is not of boolean type during logical operation, it will be converted to boolean type for calculation.

  • &&: and operation

    • Case 1: when all expressions are true, return the value of the last expression

    • Case 2: when one of the expressions is false, the value of the first false expression is returned

      var a = "abc";
      var b = true;
      var c = false;
      var d = null;
      //Situation 1
      alert(a && b);//true
      alert(b && a);//"abc"
      //Situation II
      alert(c && b);//false
      alert(b && d);//null
      
  • ||: or operation

    • Case 1: when all expressions are false, the value of the last expression is returned

    • Case 2: as long as one expression is true, the value of the first true expression will be returned

      var a = "abc";
      var b = true;
      var c = false;
      var d = null;
      	
      //Situation 1
      alert(c || d);//null
      //Situation II
      alert(c || b);//true
      alert(a || b);//"abc"
      

    &&And | also have a short circuit. Once the result is obtained, the operation will not continue.

2.5.5 ternary operators

For example: x > 0? x : -x;  // Find the absolute value of x

2.6 process control structure (condition judgment and circulation)

for, while, if else, switch, try catch, break and continue in java are used in the same way in js.

2.6.1 if structure


2.6.2 switch case structure

2.6.3 while structure

2.6.4 for structure

2.6.5 do while structure

2.6.6 break and continue

  • break can only be used in switch statements and loop statements.

  • continue can only be used in loop statements.

  • The functions of the two are similar, but continue is to terminate this cycle, and break is to terminate this layer of cycle.

  • There can be no other statements after break and continue, because the program will never execute the subsequent statements

2.7 array

2.7.1 definition of array

  • Define an empty array: var arr = [];
  • Define a non empty array: var arr1 = ["Tom", "atguigu.com", true];

2.7.2 array call

  • The angle mark of the array starts from 0 and is called directly through the angle mark. For example: alert(arr[0]);

2.7.3 length of array

  • Get the length of the array by calling the attribute length of the array

  • In the JavaScript array, as long as we assign a value to the array through the subscript of the element, js can automatically expand the capacity of the array according to the maximum subscript assigned

    var arr = [1,2,3];
    alert(arr.length);//3
    arr[5] = 15;
    alert(arr.length);//6
    

2.7.4 traversal of array

var arr = [];
arr[0] = 10;
arr[5] = 20;
for(var i = 0;i < arr.length;i++){
    alert(arr[i]);
}

2.7.5 characteristics of arrays in JS

  • Arrays can store any type of data
  • js array can be expanded automatically, and there is no cross-border problem

2.8 functions

2.8.1 function declaration and call

  • Using the function keyword

  • You do not need to specify a return value. If the function has a return value, you only need to directly use the return statement in the function body to return the required value.

  • There is no need to specify the parameter type (because js all types are declared with var)

  • Function is also an object in js. You can assign a function reference to a variable

  • When a function is called, it does not check the matching of the shape participating parameters.

    • When an argument is more than a formal parameter, the extra arguments are automatically ignored
    • When the actual parameter is less than the formal parameter, the more formal parameter value is undefined
  • Mode 1:

    • Declaration format:

      function Function name(parameter list ){
          Function body
      }
      
    • give an example:

      function sum(n, m) {
      	return n + m;
      }
      
    • Call: function name (parameter).

      var result = sum(1,2);
      alert(result);//3
      
  • Method 2: anonymous function

    • Declaration format:

      var Variable name = function(parameter list ){
          Function body;
      }
      
    • Example 1:

      var add = function(a,b){
          return a+b;
      }
      
    • Example 2:

      var info = function(){
          alert("Good things are about to happen“);
      }
      
    • Call: variable name (argument value)

      var result = add(1,2);
      alert(result);
      
      info();
      

      Anonymous functions are often directly associated with events

2.8.2 overloading of functions

  • Note 1: when calling JavaScript functions, the system does not check the number and type of incoming parameters, so there is no overload in js

  • Note 2: once a function with the same name and different parameter numbers is defined, the function defined after * * will overwrite all the previously defined functions with the same name. * * that is, add(1,2); add(1); add (1, "ABC"); add(“abc”); add(1,”666”,true);add(); Is the same function called.

    function func1(){
    		alert("This is a parameterless function");
    }
    	
    function func1(a,b){
        alert(a);
    	alert("This is a function with parameters");
    }
    	
    func1();//The second is executed
    

2.8.3 function parameters: arguments

  • Arguments is very similar to variable formal parameters in java. It can pass an indefinite number of arguments to a function
  • The operation arguments is consistent with the operation array and is also used to receive the passed parameter values.
  • The specified parameters can be obtained through corner markers.
  • You can get the number of arguments passed in when calling the function through the length attribute of arguments.
function fun(num1,num2){
    alert(num1);//12
    alert(num2);//34
    alert(arguments.length);//4
	alert(arguments[0]);//12
    alert(arguments[1]);//34
    alert(arguments[2]);//atguigu
    alert(arguments[3]);//true
}


fun(12,34,"atguigu",true);

Exercise: define a function that can calculate the sum of all passed numerical parameters and return the corresponding value.

function sum(){
    var result = 0;
    for(var i = 0;i < arguments.length;i++){
        if(typeof(arguments[i]) == "number"){
            result += arguments[i];
        }
    }
    return result;
}

alert(sum(100,200,300));
alert(sum(100,"abc",200,300));

2.9 object

2.9.1 creation and calling of objects

  • Method 1: create with new Object()

    • format

      var Variable name = new Object();//Create an empty object instance
       Variable name.Attribute name = value;//Add a property to the created object
       Variable name.Function name = function(){}; //Add a function to the created object
      
    • Access to objects (i.e. calls to properties or functions)

      Variable name.attribute;
      Variable name.Function name();
      
    • give an example

      //Object definition
      var obj = new Object();
      alert(typeof(obj));
      
      //Declare properties and functions
      obj.name = "Tom";
      obj.study = function() {
      	alert("study hard and make progress every day");
      };
      
      //Call properties
      alert(obj.name);
      //Call function
      obj.study();
      
  • Method 2: use {} to create json objects

    • format

      var Variable name = {		  //Define an empty object
          Property name 1: value 1,	//Claim property 1
          Attribute name 2: value 2,	//Declaration attribute 2
          Function name:function(){} //Declarative function
      };
      
    • Access to objects (i.e. calls to properties or functions)

      Variable name.attribute;
      Variable name.Function name();
      
    • give an example

      //Object definition
      var obj = {
      	name:"zhangchunsheng",
      	age:18,
      	work:function(){
      		alert("I'm working....");
      	}
      };
      	
      alert(typeof(obj));
      alert(obj.name);
      obj.study();
      

2.9.2 functions are also objects

  • In JavaScript, a function also exists as a data type and is a reference data type. The function name is a reference to its memory space address.
var a = function() {
	return 2;
};
var b = a;
a.age = 18;
alert(b.age); //18

2.9.3 use of this keyword

  • In JavaScript functions, the this keyword refers to the object that calls the current function.

  • Example 1:

    var obj = {
    	name:"Tom",
    	age:18,
    	study:function(){
    		alert("study hard and make progress every day");
    	},
    	info:function(){
    		alert("name : " + this.name + ", age = " + this.age);
    	}
    };
    	
    alert(obj.name);
    obj.study();
    obj.info();
    
  • Example 2:

    var obj01 = {
    
    
    	name : "obj01 name",
    	getName : showName
    };
    var obj02 = {
    	name : "obj02 name",
    	getName : showName
    };
    function showName() {
    	alert(this.name);
    }
    
    obj01.getName();//The result is obg01 name
    obj02.getName();//The result is obje02 name
    

2.9.4 three types of ready-made objects in JavaScript

  • JavaScript built-in object

    • Array ,Date,Math,......
  • Browser object

    • window,location
  • dom object

    • document,body,button......

Chapter 3 JavaScript events

3.1 event introduction

  • What is an event?

    An event is a behavior or response triggered when a computer input device interacts with a page. Such as button clicking, form submission, mouse sliding, etc

3.2 event classification

  • **System events: * * events triggered by the system, such as the completion of document loading.
  • **User events: * * user actions, such as click, mouse in, mouse out, etc.

3.3 event triggering

  • System events are triggered by the system, such as the window.onload event.

  • User events are triggered by user actions, such as click events. The system event mainly explained here is window.onload. User events are mainly triggered when operating html documents. For a detailed list of events, refer to JavaScript - > DOM events in w3c offline documentation

3.4 common events

Function nameexplain
onloadThe loading completion event is often used for some functions after the page is loaded
onclickClick event is often used to trigger the function when the user clicks the view
onblurLoss of focus event is often used to trigger the function when the focus is lost
onchangeThe content change event is often used when the content of the drop-down list and text input box changes
onsubmitThe form submission event is often used to do some form verification during the form submission event

3.5 registration of events

  • Method 1: static registration

    The js code directly assigned to the event response through the event attribute of the tag. This method is called static registration.

    <!-- 
    	onload Event static registration
     -->
    <body	onload="alert('This is the event after the page is loaded')">
    	
    </body>
    
  • Method 2: dynamic registration
    First find the tag object through js code. Then we call it dynamic registration in the form of tag object. Event name = function() {}.

    window.onload = function(){		//After the page is loaded
    	//1. Find label objects
    	//2. Pass tag object. Event name = function() {}
    }
    

3.6 event response

3.6.1 what is event response

  • We hope we can do something when something happens. This is called event response. For example, when the user clicks a button, I pop up a box to tell the user that you have successfully clicked this button.

3.6.2 what is the response function

  • The function to be executed after the event is triggered is called the response function. How do I associate response functions with events? We often use the method of assigning functions to events. For example, when the window.onload event is triggered, we execute the pop-up dialog box

    window.onload = function(){
    	alert("The document loading is complete! ")
    }
    

3.6.3 custom event response steps

**Step 1: * * get the control object from the document object model [implemented with DOM API]

**Step 2: * * declare an event response function

**Step 3: * * assign the reference of the event response function to the event attribute of the control object

For example: window.onload = function() {}

  • Life examples
mine
Arsenal production completedIt won't explode
Buried to the designated placeIt won't explode
Trigger fuseblast
  • Corresponding to the event of the program
function
statementWill not execute
Bind to the specified controlWill not execute
Trigger eventimplement

3.6.4 trigger the event response by statically registering the event

We can also use the event attribute of the tag to trigger the response function, such as:

<a href="atguigu.com" onclick="gotoguigu()">Shang Silicon Valley</a>
//onclick triggers the gotoguigu() function

Here, we define the head tag:

//We define this function in < script > < / script >
<script type="text/javascript">
	function gotoguigu(){
		alert("I'm going to Silicon Valley ")
	}
</script>

3.7 specific event examples

3.7.1 onload event

  • Example 1: static registration
<!-- 
	onload Static registration
	onload It is called automatically after the browser kernel parses the page label and loads the data.
 -->
<body	onload="alert('This is the event after the page is loaded')">
	
</body>
  • Example 2: static registration
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
	
	<script type="text/javascript">
		function onloadFun(){
			alert("Perform function operation");
			//There may be many execution statements
		}
	</script>
</head>
<!-- 
	onload Static registration
	onload It is called automatically after the browser kernel parses the page label and loads the data.
	""Semicolon after function in;It can be added or omitted.
 -->
<body	onload="onloadFun();">
	
</body>
  • Example 3: dynamic registration
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
		
	<script type="text/javascript">
		//This is how to dynamically register the onload event
		window.onload = function(){
			alert("This is dynamically registered onload event");
		};
	</script>
</head>

<body>
</body>

3.7.2 onclick event

  • Example 1: static registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    		function onclickFun(){
    			alert("onclick Static registration");
    		}
    			
    	</script>
    </head>
    <body>
    	<!-- Static registration onclick -->
    	<button onclick="onclickFun()">Button 1(static state)</button>
    </body>
    
  • Example 2: dynamic registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    			
    		// Dynamically bind the click event of the second button
    		window.onload = function(){
    // 			1. Find label objects
    			// .getElementById(""); 	 Get the label object through the id attribute
    			var btnObj = document.getElementById("btn01");
    // 			alert(btnObj);
    // 			2. Pass tag object. Event name = function() {}
    			btnObj.onclick = function(){
    				alert("This is dynamic registration onclick");
    			}
    		}
    	</script>
    </head>
    
    <body>
    	<button id="btn01">Button 2(dynamic)</button>	
    </body>
    

3.7.3 onblur event

  • Static registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    		function onblurFun(){
    			//alert("statically registered onblur event");
    			// js provides an object console for debugging output
    			// log is the output method -- it can output any data
    			console.log("Statically registered onblur event");
    		}
    	</script>
    </head>
    
    <body>
    	<!-- Static registration onblur event -->
    	user name:<input type="text" onblur="onblurFun()"/><br/>
    	password:<input id="pwd" type="password" /><br/>
    </body>
    
  • Dynamic registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    		//Dynamic registration
    		window.onload = function(){
    			//1 get label object
    			var passObj = document.getElementById("pwd");
    			//alert( passObj );
    			//2 pass the label object. Event name = function() {}
    			passObj.onblur = function(){
    				console.log("Dynamically registered onblur event");
    			}
    		}
    	</script>
    </head>
    
    <body>
    	<!-- Static registration onblur event -->
    	user name:<input type="text"/><br/>
    	password:<input id="pwd" type="password" /><br/>
    </body>
    

3.7.4 onchange event

  • Static registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    		function onchangeFun(){
    			alert("Static registration onchange event");
    		}
    	</script>
    </head>
    
    <body>
    	Please choose the goddess in your heart:
    	<select onchange="onchangeFun()">
    		<option>Zhu Yin</option>
    		<option>Zhao Liying</option>
    		<option>Lin Zhiling</option>
    		<option>Jia Ling</option>
    	</select>
    		
    </body>
    
  • Dynamic registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    		window.onload = function(){
    			//1 get label
    			var selObj = document.getElementById("sel01");
    // 			alert(selObj);
    			//2 pass the label object. Event name = function() {}
    			selObj.onchange = function(){
    				alert("Dynamic registration onchange event");
    			}
    		}
    			
    	</script>
    </head>
    
    <body>
    	Please choose the male god in your heart:
    	<select id="sel01">
    		<option>Lau Andy</option>
    		<option>Chen Daoming</option>
    		<option>Jay Chou</option>
    		<option>Lu Han</option>
    	</select>
    </body>
    

3.7.5 onsubmit event

  • Static registration

    <head>
    		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    		<title>Insert title here</title>
    		<script type="text/javascript">
    			function onsubmitFun(){
    				alert("Verify that the form item is legal");
    				alert("Illegal form item found--Block submission");
    				
    				return false;
    			}
    		</script>
    	</head>
    	
    	<body>
    		<!-- Static registration onsubmit event
    			onsubmit Event is often used to verify whether a form item is legal. If one is illegal, the form submission should be blocked. Prompt the user where it is illegal
    			Block form submission if necessary. Just use it on the label return return false
    			Static registration return Can't save
    		 -->
    		<form action="http://www.baidu.com" onsubmit="return onsubmitFun();">
    			<input type="submit" value="static state onsubmit" />
    		</form>
    	</body>
    
  • Dynamic registration

    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    	<title>Insert title here</title>
    	<script type="text/javascript">
    		// Dynamic registration
    		window.onload = function(){
    			// Get label object
    			var formObj = document.getElementById("form01");
    // 			alert(formObj);
    			// Pass tag object. Event name = function() {}
    			formObj.onsubmit = function(){
    				alert("Dynamic registration");
    				alert("Verify the form item, find it illegal, and block submission");
    				return false;
    			}
    		}
    			
    	</script>
    </head>
    <body>
    	<form action="http://www.baidu.com" id="form01">
    		<input type="submit" value="dynamic onsubmit" />
    	</form>
    </body>
    

3.8 cancel control default behavior

  • Default behavior: after some events are triggered, the system will have a default response processing. For example:

    • The hyperlink will jump automatically after clicking
    • When the form is submitted and clicked, a request will be sent
  • How to cancel the default behavior: return false; that will do

Chapter 4 JavaScript embedding method

4.1 browser loading sequence

  • Load from top to bottom

  • If the script tag is encountered, execute the script program first, and then continue loading after execution

  • Several embedding methods are listed as follows:

4.2 method 1: embedded in the event attribute of HTML tag

<button onclick="alert('hello');">Point me</button>

Note: structure and behavior are coupled, which is not recommended

4.3 method 2: embedded in the head tag

<head>
    <script type="text/javascript">
        var btnEle = document.getElementById("btn");
        btnEle.onclick = function() {
            alert("hello");
        };
    </script>
</head>
<body>
	<button id="btn">Point me</button>
</body>

Note: generally, it is OK to use it. However, if you need to use the nodes defined in the body, you cannot get the nodes in the body tag. Because the label in the body has not been loaded at this time

4.4 method 3: embedded behind the body label

<head>
    
</head>

<body>
	<button id="btn">Point me</button>
</body>

<script type="text/javascript">
	var btnEle = document.getElementById("btn");
	btnEle.onclick = function() {
		alert("hello");
	};
</script>

Note: the node can be obtained, but it does not conform to the general habit

4.5 mode 4: use window.onload to solve the problem perfectly

  • **Window object: * * represents the current browser window

  • **onload event: * * triggered after the entire document is loaded

<head>
    <script type="text/javascript">
        window.onload = function() {
            var btnEle = document.getElementById("btn");
            btnEle.onclick = function() {
                alert("hello");
            };
        };
    </script>
</head>
<body>
	<button id="btn">Point me</button>
</body>

Note: perfect solution, recommended

4.6 mode 5: import other js files

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>load05</title>
		<!-- 5.Introduce external js file -->
		<script type="text/javascript" src="script.js"></script>
	</head>
	<body>
		<button id="btnId">SayHello</button>
	</body>
</html>

In this directory, the script.js file is declared:

window.onload = function(){
	//1. Get button object
	var btnEle = document.getElementById("btnId");
	alert(btnEle);
	//2. Bind the click event to the button
	btnEle.onclick = function(){
		//3. Pop up prompt box
		alert("Hello JS");
	};
};	

Chapter 5 DOM

5.1 what is DOM

In document object model, our browser regards the whole web page as a large object, and the labels, text, attributes, etc. in the web page are also converted into objects for management, so as to operate the web page content in an object-oriented way. So how to achieve it? This is the JS DOM to learn.

5.2 DOM standard

  • Document Object Model) * * defines standard methods for accessing and processing HTML documents** It is a unified standard formulated by W3C international organization and has different implementations in many computer languages, such as c#, PHP, Java, Ruby, perl, python, JavaScript, etc.

5.3 DOM tree

The HTML DOM treats the HTML document as a tree structure. This structure is called a node tree.

<!DOCTYPE html>
<html>
	<head>
		<title>document title</title>
	</head>
	<body>
		<a href="index.html">My link</a>
		<h1>My title</h1>
	</body>
</html>

The corresponding DOM tree is as follows:

The appellation is as follows:

elementexplain
Parent elementThe element that directly contains the current element is the parent element of the current element
Child elementThe element directly contained in the current element is the child element of the current element
Ancestral elementAll elements that directly or indirectly contain the current element are ancestors of the current element
Descendant elementThe elements directly or indirectly contained in the current element are the descendants of the current element
Sibling elementElements with the same parent element are siblings to each other

Note 1: the title node and node a in the above figure are not brothers.

Note 2: the attribute nodes href and body in the above figure are not parent-child relationships, but inclusion relationships

Note 3: the text node in the above figure is the child node of the corresponding parent node.

5.4 document object

  • Document object is an attribute of window object, which represents the current HTML document and abstracts the document into a document object.
  • The document object manages the content of all HTML documents.
  • It is a tree structure containing the whole document, with hierarchical relationship.
  • It lets us objectify all tags.
  • We can access all tag objects through document.
  • The essential method to obtain the document object is window.document, and "window." can be omitted.

5.5 what is objectification

For example, the html code here is as follows:

 <body>
	<div id="div01">div01</div>
 </body>

Simulate objectification, which is equivalent to declaring the following classes in Java:

class Node{
	private String id;		// id attribute
	private String tagName; //Represents the tag name
	private Node parentNode; //father
	private List<Node> children; // Child node
	private String innerHTML; // The content between the start tag and the end tag
}

5.6 node (Node)

  • According to the W3C HTML DOM standard, each component in an HTML document is a Node, and * * HTML document is a collection of DOM nodes** In other words, Node is the most basic unit that constitutes an HTML document.

  • Classification of nodes

    • Document node: the object obtained by encapsulating the relevant information of the entire HTML document in the DOM standard.
    • Element: the object obtained by encapsulating the relevant information of HTML tags in the DOM standard.
    • Attribute node: the object obtained by encapsulating the relevant information of HTML tag attributes in the DOM standard.
    • Text node: the object obtained by encapsulating the relevant information of HTML text in DOM standard.

  • Properties of nodes
    • NodeName: represents the name of the current node. It is a read-only attribute. If the given node is a text node, the nodeName property returns a string containing #text.

    • nodeType: returns an integer representing the type of a given node. It is a read-only attribute. 1 – element node 2 – attribute node 3 – text node

    • nodeValue: returns the current value (string) of a given node, a read-write property.

      • Element node: the return value is null

      • Attribute node: the return value is the value of this attribute

      • Text node: the return value is the content of this text node

5.7 DOM query API

5.7.1 element node

  • Query element nodes throughout the document
functionAPIReturn value
Query by id valuedocument.getElementById("id value")A specific element node
Query by tag namedocument.getElementsByTagName("tag name")Element node array
Query by name attribute valuedocument.getElementsByName("name value")Element node array

Suggested order of use: first use id to find. If there is no id, consider using name to search.

If there are no id, name and name attributes, use the tag name tag to find them.

  • Find child nodes within the scope of specific element nodes
functionAPIReturn value
Find all child nodeselement.childNodes [W3C considers line feed, IE ≤ 8 does not consider]Node array
Find the first child nodeelement.firstChild [W3C considers line feed, IE ≤ 8 does not consider]Node object
Find the last child nodeelement.lastChild [W3C considers line feed, IE ≤ 8 does not consider]Node object
Finds the child node of the specified label nameelement.getElementsByTagName("tag name")Element node array
  • Finds the parent node of the specified element node
functionAPIReturn value
Finds the parent node of the specified element nodeelement.parentNodeNode object
  • Finds the sibling node of the specified element node
functionAPIReturn value
Find previous sibling nodenode.previousSibling [W3C considers line feed, IE ≤ 8 does not consider]Node object
Find the next sibling nodenode.nextSibling [W3C considers line feed, IE ≤ 8 does not consider]Node object

5.7.2 attribute nodes

  • Read attribute value: element object. Attribute name
  • Modify attribute value: element object. Attribute name = new attribute value

5.7.3 text nodes

  • Three steps to get text values:
    • Gets the parent node of the text node
    • Get the first child node of the parent node: parentEle.firstChild
    • Get the node value of the text node: parentEle.firstChild.nodeValue
  • Common operations:
    • Read text value: element.firstChild.nodeValue
    • Modify text value: element.firstChild.nodeValue = new text value

**Exercise: * * after the user clicks the [verify] button. Verify whether the content in the user name input box is legal. The verification rule is that the user name can only be selected from numbers, letters and underscores, and the length is 5-12 digits. The page definition is as follows:

user name:<input id="username" type="text" name="username" value="1234"/> 
<button id="btn01">verification</button>

answer:

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Insert title here</title>
	<script type="text/javascript">
		// Demand, after the user clicks the [verify] button. Verify whether the content in the user name input box is legal.
		// The authentication rule is that the user name must be numeric. Letters, underlined, and 5-12 digits in length.
		window.onload = function(){
			//1 get the label object of the button
			var btnObj = document.getElementById("btn01");
			//2 object by label ο nclick=function(){}
			btnObj.onclick = function(){
			//1 get the content in the user name input box -- when we want to operate a tag, we must get the tag object first.
				var usernameObj = document.getElementById("username");
				var usernameTextValue = usernameObj.value;
				//2. Verify whether the user name is legal--- The user name must be numeric. Letters, underlined, and 5-12 digits in length
				// If you want to validate this rule, you must use regular expressions to validate it
				var patt = /^\w{5,12}$/;
				// The test method is specifically used to verify whether a string matches a regular expression
				// Returns true if there is a match
				// false is returned if there is no match
				if (patt.test(usernameTextValue)) {
				//3 prompt the user to verify the results.
					alert("The user name is legal");
				} else {
					alert("Illegal user name");
				}
			}
		}
	</script>
</head>
<body>
	user name:<input id="username" type="text" name="username" value="1234"/> 
	<button id="btn01">verification</button>
</body>

Note: for the use of regular expressions, see the distributed document: w3cschool rookie tutorial new version. chm - JavaScript tutorial - JavaScript RegExp object - complete RegExp object reference manual.

5.8 DOM addition, deletion and modification API

APIfunction
document.createElement("tag name")The element node is created and returned, but is not automatically added to the document
document.createTextNode("text value")Create a text node and return, but it is not automatically added to the document
element.appendChild(ele)Add ele after all child nodes of element
parentEle.insertBefore(newEle,targetEle)Insert newelement before targetEle
parentEle.replaceChild(newEle, oldEle)Replace the old child node with the new node
parentEle.removeChild(childNode)Deletes the specified child node
element.innerHTMLRead and write the contents of the start tag and end tag
element.innerTextRead and write the text in the start tag and end tag

Example: add node

Example: replace node

Example: insert node

give an example:

<script type="text/javascript">
	// You need to manually create a label object through code: < div > Master Kang is so handsome</ div>.  Then add this label to the window to display
	window.onload = function() {
		// The createElement method creates a label object
		var divObj = document.createElement("div"); // <div></div>
		// Add the content divObj.innerHTML = "Master Kang is so handsome!"; / /< Div > Master Kang is so handsome</ div>

		// Create a string as a node object through code
		var textNode = document.createTextNode("Master Kang is so handsome!");

		divObj.appendChild(textNode); //< div > Master Kang is so handsome</ div>

		// Add the div tag to the body tag
		document.body.appendChild(divObj);
	}
</script>

5.9 innerHTML, supplementary description of innerHTML

  • Returns all the contents from the start position to the end position of the object, including HTML tags.

  • Read element internal HTML code

    • Element object.innerHTML
  • Modify element internal HTML code

    • Element object. innerHTML=HTML code

Generally, nodeValue is used to obtain the content of input tag, and innerHTML is used to obtain the content of double tag

Keywords: Java Javascript Front-end

Added by torleone on Wed, 08 Dec 2021 21:40:30 +0200