Java0 Basics_ day17_ Java web front end_ JavaScript

Tags: JS, JavaScript

1.JS overview

JS, the full name of JavaScript, is a language specification specially used for browser parsing and execution. It belongs to event driven language.

This study mainly includes four parts: JS basic syntax, DOM programming, BOM programming and JSON format.

2.JS basic syntax → ES6 specification / ECMA-262 specification

First of all, make it clear that JS is a weakly typed language, which is different from the strongly typed language of java. Variables in java must be declared as a specific type before use, and then always placed in the container of the corresponding type. JS does not need to specify a specific type. The type of variables is dynamically determined by the value given on the right side!

2.1 data type and variable

Part I: overview of data types

Data types in JS are divided into original types and reference types:

  • Original type: String, Boolean, Number, Undefined, Null
  • Reference type: Object and its subclasses

In particular, we use the typeof variable name to find the type of the variable:

typeof a 
Result 1 out of 6:"undefined","number","object","boolean","string","function"

[note] JS uses = = to judge whether the values are equal, and = = = to judge whether the values and types are completely consistent.

var i;
alert(typeof i);
var x = false;alert(typeof x);
var y = 10;alert(typeof y);
var z = null;alert(typeof z);//Return to "object";
var w = "sadfd";alert(typeof w);
var obj = new Object();
alert(typeof obj);//Return to "object";
function a(){}
alert(typeof a);//"function"
alert(typeof a());//"undefined"

The following is an equal sign test:

alert(typeof null);//"object"
alert(typeof undefined);//undefined""
alert(typeof NaN);//number""
alert("I am==Split line");
alert(null==NaN);//false
alert(null==undefined);//true????????
alert(undefined==NaN);//false	
alert("I am===Split line");
alert(null===NaN);//false
alert(null===undefined);//false
alert(undefined===NaN);//false

alert("I am true Split line of and 1");
alert(1==true);//true is similar to the equals method;
alert(1===true);//false

Part II: Variables

First point: variable declaration:

var Variable name;

[note] if a variable is declared but not assigned, it defaults to undefined. If a variable is used without declaration, an error will be reported.

Second point: variable classification

Variables in JS are divided into global variables and local variables. The difference is whether they are declared in the function.

In particular, if a value is directly assigned within a function but is not declared, JS defaults to a global variable!

[Note 2] global variables consume memory. If not necessary, local variables are recommended.

Part III: detailed explanation of data types

First: Number class

The Number class can be: Infinity, NaN, 3, 9.44, - 33, - 4.44;

NaN: when the expected result is a number but it is found that it is not a number after operation, NaN is returned:

var a =3;
var b ="dasf";
alert(a/b);//NaN

Number has four key functions:

	isNaN(a) //Judge whether a is of NaN type. If isNaN is true, it is a NaN
	//parseInt(),parseFloat(),Math.ceil();
	alert(parseInt(3.33));
	alert(parseInt("3.33"));
	alert(parseFloat(3.333)+22);
	alert(Math.ceil('-2.22'));
	alert(Math.ceil('2.22'));

Second: Boolean class

The most important is the Boolean() function, which converts non Boolean types to Boolean types:

	//Summary: "yes" is converted to true; If not, it will be converted to false;
	alert(Boolean(1));//true
	alert(Boolean(0));//false
	alert(Boolean(""));//false
	alert(Boolean(" "));//true;
	alert(Boolean(null));//false
	alert(Boolean(undefined));//false
	alert(Boolean(NaN));//false
	alert(Boolean(Infinity));//true!!!!
	while(0.000000000000000){//It is considered that 0.0 = = 0;
		alert("hh");
	}
	alert(typeof null)//Return to "object"

Third: Undefined class

This type has only the value undefined, which can be assigned by default or manually.

var uni;
alert(typeof nui);//"unidefined";
var un2 = unidefined;

Fourth: String class

Properties:
        prototype attribute   
        constructor attribute
 Function:
        toString();
        valueOf();
        toLocalString();

In JS, there are two methods to create a String, called small String and large String

var lowString = "saf";
alert(typeof lowString);//"string"
var bigString = new String("jjj");
alert(typeof bigString );//"object"

In any case, they share the following methods:

alert("abcdefgh".substr(2,4));//A string of 4 characters starting from 2;
alert("abcdefgh".substring(2,4));//Substring from 2 to 3;
alert("ABCDEFFEDBCA").repalce("A","g")//Replace the first character; Regular expressions can be used;
alert("abcdefgh".indexOf("a"));//Substring matching;
alert("ABCDEFFEDBCA").toLowerCase());//Convert all to lowercase;

Fifth: Object class

This class is the ancestor of all reference classes, and the most important attribute is the protocol attribute.

First: how to create objects?

Step 1: create a custom class

Method 1: function ObjectClass(name,id){
    this.name = name;
    this.id = id;
}
Method 2: ObjectClass2 = function(name,id){
     this.name = name;
     this.id = id;
     this.getId = function(){
        return this.id;
        }
}

Step 2: new object

var x1 = new ObjectClass("Zhang San",300);
var x2 = new ObjectClass2("Li Si",600);

It is worth noting that if ObjectClass() is called directly, it is a function call, and new is the object creation.

Step 3: attribute access

Method 1: alert(x1.name);
Method 2: alert(x2["id"]);

Second: how to expand the properties of classes at will

Point 1: expand custom classes

ObjectClass.protype.getName = function(){

    return this.name;
}
alert(x1.getName());//Note that the expansion here is the method;

Second: expand built-in classes

String.protype.prt = function(){

    return "nihao";
}
alert("sadf".prt());//Note that the expansion here is the method;

Sixth: Null class

2.2 function

In JS, statements that complete certain functions are called functions. Keyword: function

First: Grammar

Method 1:
function Function name(parameter list ){Function body}
Method 2:
Function name= function (parameter list ){	Function body}

Because JS is a weak type, you don't need to add the function parameter type and return value type!

Second: function assignment process

function sum(a,b){
	return a+b;
}	

var s = sum(1,2);
alert(s);

var t= sum("jaav+");//Assign to the first formal parameter, and the second default assignment is undefined;
alert(t);
var t3= sum();//Return NAN value, a specific non-existent value, which is not a parameter;;;
alert(t3);

alert(sum(100,9,3));//Returns the sum of the first two numbers;

Third: the process of resolving function duplicate names

function test(s){alert("test text");}
function test(){
	alert("test");
}//Functions in JS cannot have the same name, otherwise the previously defined functions will be directly overwritten at this time;
test(300);

Fourth: void usage of function

void is used to realize the requirement that there is a hyperlink style, but it does not jump after clicking.

<a href="javascript:void(0)" onclick = 'window.alert("Click successfully")' >

The addition of javascript here means to tell the browser that my paragraph is my own code, not a pathname.

You will see this effect:

2.3 control statement

In addition to the selection (if else, switch) and loop (for, while, break and continue) in JAVA, JS has with and for... In statements, which can be understood simply!

//1. Traverse the array
var arr = [1,2,false,"fasdf"];
for(var i in arr){
    alert(arr[i];//i is the array subscript
}

//2. Iteration object for...in

User = function(name,pwd){
			this.name=name;
			this.pwd=pwd;}
var u =new User("zhagnsan",12456);
for(var shuxing in u){
    alert(u[shuxing]);
    alerrt(u.shuxing);}//Note that shuxing is automatically of type string;


//3. Automatic assignment
with(u){
    alert(name);//Equivalent to alert(u.name);}

2.4 events

JS is an event driven statement. How do you understand it? It can be understood that the browser is a monitor, waiting for the user to send actions such as clicking the mouse and typing the keyboard all the time. Once the specified action is sent, some operations will be performed, which realizes interactivity.

2.4.1 event classification

Classification:
blur
focus


click
dbclick

mousedown
mouseover
mousemove
mouseout
mouseup

reset
submit

change Drop down list changes/Text box content changes
select The text is selected
load whole html Occurs after all page elements of the page have been loaded

The related concept is event handle. We say that an event is an action that actually occurs, which can be understood as calling a function. The related event handle refers to the action object. The rule is to add the on keyword before the event. For example, onclick is to click the event handle.

2.4.2 event registration

Associating events with the rules you want to define is called event registration. For example, registering onclick with the printout "hello", which is a case.

//Registration method 1
<input type = "button" value="hello onclick='sayhello()'"/>
//Register here and call it after the event occurs;
function sayhello(){
	alert("sfa");}
//The second way: pure js code
<input type ="button" value="hello2" id="mybt"/>
<script type="text/javascript">
	/* 
	  Step 1: get the button object;
	 */
	function doSome(){
		alert("dosome");
	}
		var bnobj = document.getElementById("mybt");
		//Step 2: assign a value to the onclick attribute of the button object
		bnobj.onclick = doSome;
//Be careful not to add parentheses, bnobj.onclick = doSome(); If it is wrong, the function will be executed first!!
		//This line of code means to register the doSome function to the onclick event;
		var s= document.getElementById("mybt");
		s.onclick = function (){//Anonymous function
			alert(434);
		}
		//One line code:
		document.getElementById("mybt").onclick = function(){
			alert("kkk"); 
		}

</script>
<script type="text/javascript">
	window.onload = function (){
		document.getElementById("mybt").onclick = function(){
			alert("sajdfjsf");
		}			
	}
//When the page is opened, the large function is registered to onload. After onload is executed, the internal onclick is registered when the large function is executed;
</script>
<input type="button" value="ha-ha"  id="mybt"/> 

[execution sequence] first of all, it is clear that JS code is executed from top to bottom. onload registration is on the left, which means that the function bound on the right will be executed after the button at the bottom of the page is loaded, and then when the button click event occurs, the internal function will be executed, that is, pop-up window.

Related to this is the concept of callback function. Its essence is to look at problems from different angles. It is understood that it is a function called by others by writing its own code. Take java as an example:

public class hh(){
    public static void main(String[] args){
	    run();//From my point of view, run is a forward call;}
public static void run(){
 System.out.println("run...");//From the perspective of run, I write that it is called by others, so I am a callback function;}
				

2.4.3 get the specified object

In java, everything is an object, and the same is true in JS, such as label object, click button object and so on.

<script>
<input type ="button" value="hello2" id="mybt"/>
<script type="text/javascript">
	document.getElementById("mybt").onclick = function(){
		alert("kkk"); }
</script>

2.5 item: Enter key capture demonstration

Demand: capture the user to press enter in the text box, and the pop-up window will display

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Capture enter</title>
</head>
<body>
<script type='text/javascript'>

window.onload = function(){
	var x = document.getElementById("username");
	x.onkeydown = function(event){
		//Here, on must be added to the left to be the time handle;
		//Here, when the event is not written, it is equivalent to passing the keydown event;
		//Here, event is the event object from the browser new, and the event bound on the left;;
		//For keyboard events, there is a keycode attribute;
		// document.getElementById("login").onclick = function(){
			// alert(event.keyCode);
			//Improvement: obtain key value; esc value is 27 and enter key is 13;
			//Click enter to log in:
			// document.getElementById("login").onclick = function(){
			// 	alert("login succeeded, Congratulations");
			// }
			// alert(event.keyCode);// Note that this must be an uppercase KeyCode!!
			// 	// document.getElementById("login").click();
			// alert(event.keyCode);
			 if(event.keyCode===13){
			
				alert("Testing");
			 }		
		//}
		 // document.getElementById("login").onclick();
	}
}

</script>
<input type="text"  value = "enter one user name" id="username" />
<BR/>
<input type="button"  value = "Sign in" id="login" />


</body>
</html>

3.DOM programming

DOM is the Document Object Model, which sets the properties of the nodes in the web page, and its top-level object is document.

3.1 modifying node values

//Realize the content exchange of click up and down text boxes;
window.onload = function(){
	document.getElementById("bu").onclick = function(){
		// alert(document.getElementById("te").value);// Attribute cannot be parenthesized. The value here is essentially the value of the input text box below!
		// alert(document.getElementById("te").value = "lisi");// Attribute cannot be parenthesized. The value here is essentially the value of the input text box below!
		// alert(document.getElementById("te").value );// Attribute cannot be parenthesized. The value here is essentially the value of the input text box below!
		// //Modify the value of. Value!!!
		alert(typeof document.getElementById("te").value);
	var x =document.getElementById("te").value;
	document.getElementById("te").value = document.getElementById("te2").value;
	document.getElementById("te2").value = x;
		// document.getElementById("te2").value = document.getElementById("te").value;
		// document.getElementById("te").value ="";
	}
}

</script>

<!-- <input type="button" value="nihao" id="one"/> -->

<input type="text"  id="te"/>
<br/>
<input type="text"  id="te2"/>	<br/>
	<input type="button" value="Context transfer" id="bu"/>
	<input type = "text" value="nihoa" onblur ="alert(this.value)"/>
	<!--The loss of focus here refers to cursor removal!, this Represents the current input Object;-->

3.2 innerHtml and innerText values

<script type="text/javascript">
	//innerHTML and innerText are div attributes. The former will be regarded as html code and the latter as string;
	window.onload = function(){
		document.getElementById("btn").onclick = function(){			
			// alert(11);
			//The first step is to obtain div;
			var x =document.getElementById("div1");
			//Step 2: use the innerHTML attribute to set the internal content of the element;
			x.innerHTML = "<h1>How do you do</h1>"; //As html code
			// x. InnerText = "< H1 > Hello < / H1 >"// Treat all as strings;
		}	
	}

//Debugging error: open the console in F12 to see if there is an error;

</script>
<input type="button"  value="set up div"  id="btn" />
<div id="div1">  </div>

3.3 checkbox items

Requirement: click Select all to select all, and then click to cancel all; At the same time, if all are selected, the select all button will light up automatically.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>checkbox</title>
	</head>
	<CENTER>
	<body>
		<script type="text/javascript">
		window.onload = function(){
			var names = document.getElementsByName("aihao");//Modify the position because you need to click the first box with an irrelevant mouse;
			var zt = document.getElementById("allcheck");
			zt.onclick = function(){
				for(var i =0;i<names.length;i++){
					names[i].checked = zt.checked;
				}
			}
			var totalcount = names.length;
			
			for(var i =0;i<names.length;i++){//This for loop is performed when the page is loaded;
				names[i].onclick = function(){//This for loop searches globally after clicking a button;
				var checkcount =0;
				for(var i =0;i<names.length;i++){
					if(names[i].checked){
						checkcount++;
					}
				}
				zt.checked = (checkcount==totalcount);
				}	
			}}
		</script>
		<input type="checkbox" id="allcheck"/>Select all<br/>
		<input type="checkbox" name="aihao"/ >Hot head<br/>
		<input type="checkbox" name="aihao"/>having dinner<br/>
		<input type="checkbox" name="aihao"/>drink<br/>
		
	</body>
</CENTER>	
</html>

The following is a summary of the initial attempt:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>checkbox</title>
	</head>
	<CENTER>
	<body>
		<script type="text/javascript">
		window.onload = function(){
			//Detecting the state of the first tag;
			var names = document.getElementsByName("aihao");//Modify the position because you need to click the first box with an irrelevant mouse;
			//From top to bottom:
			var zt = document.getElementById("allcheck");
			zt.onclick = function(){
				// zt.checked = (zt.checked?false:true);
				//There is no need to manually copy here. The browser already knows that you click checkedbox=true/false;
				// zt.checked = true;	
				for(var i =0;i<names.length;i++){
					names[i].checked = zt.checked;
				}
			}
			var totalcount = names.length;
			
			// for(var i =0;i < totalcount;i++){
			// 	if(names[i].checked){
			// 		checkcount++;
			// 	}
			// }
			// zt.checked = (checkcount==totalcount);
			for(var i =0;i<names.length;i++){//This for loop is performed when the page is loaded;
				names[i].onclick = function(){//This for loop searches globally after clicking a button;
				var checkcount =0;
				for(var i =0;i<names.length;i++){
					if(names[i].checked){
						checkcount++;
					}
				}
				zt.checked = (checkcount==totalcount);
				}	
				// zt.checked = (checkcount==totalcount);
				// alert(names[i]);
				//Test, every click
			}
				
		}				
			// for(var i =0;i<names.length;i++){
			// 	var checkednum =0;
			// 	if(names[i].checked){
			// 		checkednum++;
			// 	}	
			// }
			// zt.checked=(checkednum==total);
			
		// 	//Bottom to top:
		// 	var total = names.length;
		
		// 	for(var i =0;i<names.length;i++){
		// 			var checkcount = 0;
		// 		names[i].onclick = function(){
		// 			checkcount = (names[i].checked?checkcount++;checkcount--);
		// 			alert(checkcount);
		// 		}
		// 	zt.checked = (checkcount == total?true;false);		
		// 	}		
		}

		</script>
		<input type="checkbox" id="allcheck"/>Select all<br/>
		<input type="checkbox" name="aihao"/ >Hot head<br/>
		<input type="checkbox" name="aihao"/>having dinner<br/>
		<input type="checkbox" name="aihao"/>drink<br/>
	</body>
</CENTER>	
	
	
</html>

3.4 get the value of the drop-down list

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
		window.onload = function(){
			var list = document.getElementById("hh");
			list.onchange = function(){
				alert(list.value);
			}	
		}
		</script>
		<!-- 	//Both upper and lower methods can -- >
		<select onchange="alert(this.value)" id="hh">
			<option value="">Please select a province</option>
			<option value="001">Chongqing City</option>
			<option value="002">Jiangsu Province</option>
			<option value="003">Shangha City</option>
		</select>
	</body>
</html>

3.5 built in clock

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Show web clock!</title>
	</head>
	<body>
		<script type="text/javascript">
	// 	/*JS built-in support class Date;
	// 	*/
	// 	var nowtime = new Date();
	// 	 document.write(nowtime);// Analogy java
	// 	 //Sat Nov 27 2021 21:59:25 GMT+0800 (China standard time)
	// 	 nowtime = nowtime.toLocaleString();
		 
	// 	 document.write(nowtime);// 9:41:31 pm on November 27, 2021
		 
	// 	 //How to customize date format;
		 
	// 	 var t =new Date();
	// 	 var year = t.getFullYear();
	// 	 var month = t.getMonth();// Month is 0-11;
	// 	 var day = t.getDay();// The date is the day of the week, and Saturday is 6;
	// 	 //0~6;
	// 	 //day should be dayOfWeek;
	// 	 document.write("<BR/>");
	// 	document.write(year + "year" + month + "month" + day + "day" + t.getDate() + "sign");
		
	// 	//How to get the total milliseconds: from 1970 1-1 0:0:0
	
	// 	alert(t.getTime());
	// 	//Function: return timestamp;
		<script type="text/javascript">
			// function displaytime(){
			// }
		// displaytime();
		window.onload = function(){
			document.getElementById("button").onclick = function(){
					var time = new Date();
					var Strtime = time.toLocaleString();
					document.getElementById("divtime").innerHTML = Strtime;
				
			}
			
		}
		</script>
		<input type="button" value="Display time" />
		<!-- //Note the quotation marks; -- >
		<BR/>
		<div id="divtime"></div>
	</body>
</html>

According to this, you can complete the clock small project. Click the start button, the clock starts and ends, and the clock stops:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
	<script type="text/javascript">
		function displaytime(){
			 // time= ;// Display the current time;
			var Strtime = new Date().toLocaleString();
			document.getElementById("divtime").innerHTML = Strtime;
		}
		function start(){
			//Call the function every second;
			v = window.setInterval("displaytime()",1000);	
		}
		function stop(){
			//Stop and record the current time;
			window.clearInterval(v);//method;
		}
	</script>
		<input type="button"  id = "jj" value="Display time" onclick="start()"/>
		<input type="button"  id = "sop" value="Stop button" onclick="stop()"/>
		<BR/>
		<div id="divtime" ></div>
		
		
	</body>
</html>

3.6 built in Array class

var a = [];
var a2 = [1,2,false,"dsf"];
alert(a2.length);
alert(a.length);

alert(a2[a2.length]);//undefined
//New creation method;
var s = new Array(3);//This 3 represents the length of the array!!;
alert(s.length);


var s2 = new Array(99,8,7);//This indicates that the length of the array is 3, 3 elements!!;

alert(s2.length);
alert(s2[0]);
//Array splicing
alert(s2.join("-"));//Connect in sequence


//push adds elements to the tail;
s2.push(100);
alert(s2);

//Pop: pop up end element
alert(s2.pop());
alert("Count Reg"+s2.length);

//JS array automatically simulates the data structure, first in and last out;
s2.reverse();
alert(s2);

3.7 regular expressions

regular expression is used for string matching. It is supported in java, javascript and python.

First: basic rules

.Matches any character except the newline character
\w Match letters or numbers or underscores or Chinese characters
\s Match any whitespace
\d Match number
\b Matches the beginning or end of a word
^Start of matching string
$End of matching string

*Repeat zero or more times
+Repeat one or more times
?Repeat zero or once
{n}repeat n second
{n,}repeat n Times or more
{n,m}repeat n reach m second

//antonym;
\W Match any character other than letters, numbers, underscores or Chinese characters
\S Matches any character that is not a white space character
\D Matches any non numeric character
\B The match is not at the beginning or end of a word
[^x]Match except x Any character other than
[^aeiou]Match except aeiou Any character other than these letters

Second: create regular expressions

Method 1: var reg = /regular expression /flags;
Method 2: var regexp = new RegExp('regular expression ',"flags");
//flags:
	g: Global matching
	i: ignore case
	m: Multi line search;[]ES Designated only after the specification is formulated; If above/When is a regular expression in, m out-of-service;

Third: test() method of regular expression

<script>
window.onload = function(){
		var reg = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/;
			// reg.test(document.getElementById("email").value)?alert("legal"): alert("illegal!");
		var x ;
			//Implementation effect: if the input is correct, it will return to legal, otherwise it will remind you to re-enter, and the word "please re-enter" will be displayed when the cursor is placed in the input box;
		document.getElementById("btn").onclick = function(){
				if(!(x=reg.test(document.getElementById("email").value))){
					document.getElementById("emailtest").innerText = "Illegal illegal";
					document.getElementById("email").onfocus = function(){
						document.getElementById("emailtest").innerText="";
					}
				}
				else{
				document.getElementById("emailtest").innerText = "Congratulations, it's finally legal";	
				}
				// else{
				// 	document.getElementById("emailtest").innerText = "very legal";
				// }	
			}
			//Add the function to display the initial value of the content when the cursor returns;
		}
</script>
    <input  type="text"  id="email" /><br/><br/>
    <input  type="button"  value="yanzheng" id="btn" /><br/><br/>
    <span id ="emailtest"  style="color:red;font-size:33px" > </span><br/><br/>

3.8 trim extension of string

window.onload = function(){
	document.getElementById("password").onclick = function(){
		var s = document.getElementById("username").value;
		s = s.trim();
		alert("Object is="+s+"=object");
		alert("http://www.baidu.chhomg/".replace(/\//g,"-"));
		//The ^ and $symbols cannot be added here because they are part of the string;
		//What if IE can't trim?
		//Extended trim function;
	}		
}
String.prototype.trim = function(s){
	// var reg = /^\S*\S*$/;
	// alert("I am an overridden trim method");
	//This represents this string
	return this.replace(/^\s*/,"").replace(/\s*$/,"");
	//Merge: return this.replace(/^\s|\s * $/, "");
	//Note here that \ ^ and $/ can be separated, regular expressions;
}

</script>
<input type="text" id="username"/>
<input type="button"  value= "Sign in" id="password"/>

3.9 major projects: form verification

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
		window.onload = function(){
			var username;
			document.getElementById("bd").onclick = function(){
				username = document.getElementById("shurukuang").value;
				document.getElementById("sp").innerText = isgood(username);
				document.getElementById("shurukuang").onfocus = function(){
					document.getElementById("sp").innerText = "";
					if(isgood(username)=="Login failed"){
						document.getElementById("shurukuang").value="";
					}
				}
			}
			//Write a different step of debugging;	
		}
		
		isgood = function (username){
		if(username!="" && username.length<=14 && username.length>=6 ){
			//You can write if username directly!
			//Pay attention to remove the front and back blanks;
			var regexp = /^[0-9a-zA-Z]*$/;
			if(regexp.test(username)){
				if(document.getElementById("pwdinput").value===realpwd){
					return "Validation succeeded";
				}
			}
		}
		return "Login failed";
		}
		var realpwd = "123456";
		
		<!-- <span id ="emailtest"  style="color:red;font-size:33px" > -->
		
		</script>
		<form action ="http://www.baidu.com" id="form"  method = "post"></form>
		user name:<input type="text" name="username" id="shurukuang"/><br/><br/>
		password:<input type="password" name="password" id="pwdinput"/>
		<!-- <span id="sp" style="color:red;font-size:23px"></span><br/><br/> -->
		<span id ="sp"  style="color:red;font-size:33px" ></span><br/><br/>
		<input type="button" value="Submit" id="bd"/><BR/><BR/>
		<input type="submit" value=Sign in""/><BR/><BR/>
		<input type="reset" value=Reset""/>
	</body>
</html>
<!--DIV One line, span Add a line-->

4.BOM programming

bom, that is, browser object model, browser object model, such as closing browser window, moving forward and backward, obtaining URL parameters of address bar, etc. all belong to this model, which can be understood as functions in the box on the body of the browser.

4.1 window.open and close methods

<script type="text/javascript">	
</script>
<input type="button" value="Open Baidu(New window)" onclick="window.open('http://www.baidu.com/')"/>
<input type="button" value="Open Baidu(self current window)" onclick="window.open('http://www.baidu.com/','_self')"/>
<input type="button" value="Open Baidu(blank New window)" onclick="window.open('http://www.baidu.com/','_blank')"/>
<input type="button" value="Open Baidu(parent parent window)" onclick="window.open('http://www.baidu.com/','_parent')"/>
<input type="button" value="Open Baidu(top Top level window)" onclick="window.open('http://www.baidu.com/','_top')"/>
<input type="button" value="open" onclick="window.open('Open test.html')"/>
<input type="button" value="guanbi(New window)" onclick="window.close('Open test.html')"/>

4.2 pop up prompt box

<body>
	<script type="text/javascript">
	function del(){
		var ok = window.confirm("Are you sure to delete the data?");
		alert(ok);
	}
	//if(window.confirm("are you sure to delete data?"))
	</script>
	<!--Users must be reminded when deleting;-->
	<input type="button" value="Popup Message " onclick="del()"/>
	
</body>

4.3 history window

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h1>niahao</h1>
	</body>
	<input type="button" value="Retreat" onclick="window.history.back()"/>
	<!-- <input type="button" value="Retreat" onclick="window.history.go(-1)"/> -->
    <input type="button" value="forward" onclick="window.history.go(1)"/>
</html>

4.4 top level window settings

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		4444444
		<!-- If it is not a top-level window, set it to the top-level window -->
		<script type="text/javascript">
			function setTop(){
				console.log(window.top!=window.self);//false;
				if(window.top!=window.self){
					
					window.top.location=window.self.location;
					// window.top=window.self;
					//window.top is the top-level window setting window
					//window.self is the top-level window 2
					// window.top.href=window.self;
				}
				
			}
		</script>
		<BR/><input type="button" onclick ="setTop()" value="If set to top-level window"/>
		<!-- <iframe src="Top level window 2.html" width="800px" height="500px"></iframe> -->
	</body>
</html>

4.5 how the browser gets the URL

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
		/*Which can send requests through the browser web server:
		 1.Form form
		 2.Hyperlinks
		 3.document.location
		 4.window.location
		 5.window.open("url")
		 6.Enter the URL directly and press enter;
		 6.All the above data can carry data. The form is dynamic and the hyperlink is static;*/
		gobaidu = function (){
			// window.open("http://www.baidu.com");
			//Get the parameters in the address bar;
			// var locationObj = window.location;
			// locationObj.href = "http://www.baidu.com";
			// window.location.href = "http://www.jd.com";
			// document.location.href = "http://www.taobao.com";
			document.location = "http://www.qq.com";
		}
		</script>
		<!-- <iframe src="Top level window 2.html" width="800px" height="500px"></iframe> -->
	</body>
		<input type="button" value="Baidu" onclick="gobaidu()"/>
		<!-- <input type="button" value="Baidu" onclick="window.open(www.baidu.com)"/> -->
		<!-- <input type="button" value="Baidu" onclick="http://www.baidu.com"/> -->
</html>

5.JSON details

5.1 json overview

json, javascript object notation, pronunciation: Jason, as a common data exchange format with XML format, is widely used in actual development. It is small, easy to parse and lightweight. XML is large and has strict syntax. It is generally used as a bank. For example, we have seen web.xml in the servlet at the back end of javaweb.

5.2 creating json objects_ Method 1

//Single json object
var jsonobj = {
			"sno":"110",
			"sname":"zahgnsan",
			"sex":"male"		};
alert(jsonobj.sno+","+jsonobj.sname+","+jsonobj.sex);

//JSON object array
var students = [
	{"sno":"110","sname":"Zhang San","sex":"female"},
	{"sno":"200","sname":"Wang Wu","sex":"male"},
	{"sno":"300","sname":"Li Si","sex":"male"}
		];//Pay attention to the use of semicolons and commas;
//ergodic
for(var i=0;i<students.length;i++){
	alert(students[i].sno+","+students[i].sname+","+students[i].sex);
}
//json nesting
var user = {
	"usercode":"110",
	"username":"zahgnsan",
	"sex":"male",
	"address":{
		"city":"Beijing",
		"street":"Daxing",
		"zipcode":"40234",
		"aihao":["smoke","drink","tt"]//My hobby is array, others are json
	}	
};
alert(user.address.city);

[note] JSON is represented by {} in JS. The core is attributes and values, and each attribute is separated by commas;

five point three   Create json object_ Method 2_ Use of Eval function

eval is a built-in function of js. It is used to interpret and execute a string as a js command. Generally, in actual development, it is a string in json format passed from java, which needs to be converted into a json object.

window.eval("var i=100;");
alert("i="+i);//100
//The data queried by the JDBC connection database is spliced into a JSON format string in the java program, but it is not a JSON object!
//You can use the eval function to convert it into a JSON object;
var fromjava = "{\"name\":\"zhagnsan\",\"password\":\"200\"}";//From jaVa
window.eval("var jsonObj ="+fromjava);//Create a new object;
alert(jsonObj.name);
alert(jsonObj.password);

5.4 major projects: json table creation

<!DOCTYPE html>
<html>
	<CENTER>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script type="text/javascript">
		var jsonObj ={
			"total":3,
			"emps":[
			{"empid":100,"name":"smith","sal":800}	,
			{"empid":200,"name":"haha","sal":900}	,
			{"empid":300,"name":"zdafsf","sal":3000},
			]	
		};
		window.onload = function(){
			document.getElementById("display").onclick = function(){	
				// window.eval("<tbody>");
				var html="";
				for(var i=0;i<jsonObj.total;i++){
							var rowInfo = jsonObj.emps[i];
							html  += "<tr>";
							html  += "<td>"+rowInfo.empid+"</td>";
							html  += "<td>"+rowInfo.name+"</td>";
							html  += "<td>"+rowInfo.sal+"</td>";
							html  += "</tr>";		
							// window.eval(str);// To be added to the innerHtml of Tbody;
			}
			document.getElementById("tby").innerHTML = html;
			document.getElementById("count").innerText = jsonObj.total;
		}}
		</script>
		<input type="button" value="Display employee information" id="display"/>
		<h2>Employee information form</h2>
		<hr>
		<table border="4px">
			<th>Employee number	</th>
			<th>Employee name	</th>
			<th>Employee salary	</th>
			<TR/>
			
		<tbody id="tby">
		</tbody>	
			
			
		</table>
		in total<span id="count">0</span>Number of articles
	</body>
	</CENTER>
</html>
<!-- <tbody>
				<tr>
					<td>100</td>
					<td>smith</td>
					<td>800</td>
				</tr>
				<tr>
					<td>200</td>
					<td>haha</td>
					<td>900</td>
				</tr>		
						
				<tr>
					<td>300</td>
					<td>zdafsf</td>
					<td>1000</td>
				</tr>		
				
			</tbody> -->

6. Summary

6.1 js commissioning

In js development, you must write and debug step by step, that is, when testing, open F12 of the browser, look at the error information of the console and locate the error.

six point two   What is the difference between [] and {} in JS  

  [] is an array in {} JSON format;
         java array: int[] a ={1,2,3,4,5};
         js array: var x =[1,2,3,4];
         JSON: var obj ={"name":"99","pass":003};
         JSON is a data exchange standard, which exists in the form of an object in JS;
         var obj ={"name":"99","pass":003};
         Method 1: obj.name;
         Method 2: obj["name"]

6.3 follow up learning route

 // Generally, learn JS framework:
         XML
         servlet
         JSP
         EL
         JSTL
         AJAX
         MVC
         Dynamic agent
         Maven
         -->
        <!-- Framework Spring, Spring MVC, mybatics and ssm -- >

In particular, when state-owned enterprises look at javase, small companies ask for projects and start directly; Big companies ask about bias principles; sql optimization.

 

Tags: Java Back-end

Posted on Sun, 28 Nov 2021 00:57:35 -0500 by southofsomewhere