This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

1. DOM manipulation

In an HTML page, many tags are used to plan the page.

Each tag has its own purpose, if we want to change the value of a tag dynamically. Then we need to find the tag element on the page.

Finding this element was a problem, and the engineers at the W3C suddenly saw a big tree. What should I do if I want to find a leaf?

“Follow the path”, the main trunk has branches, each branch has many small branches, as long as the structure of the branch is sorted out clearly, any leaf is not difficult, some inspiration from leaves and trees, engineers meeting to discuss this theory “document object model”.

Document object model (dom), that is, all the tag element in the page as an object (a leaf), the main trunk section is defined as the root point (the root element), all tags are extending from the root element out and clear structure, is no longer difficult to find a label At the top of the node in the tree, the node is the root node (the root), Each node has a parent (except for the root node). Any node can have any number of children. Siblings are nodes that have the same parent

<html>
<head>
<meta	charset="utf-8">
<title>DOM tutorial</title>
</head>
<body>
<h1>Section 1: THE HTML DOM</h1>
<p>Hello	world!</p>
</body>
</html>
Copy the code
From the HTML above:<html>A node has no parent node; It's the root node<head>and<body>The parent node of<html>Node text node "Helloworld!" The parent node of<p>Node and:<html>A node has two children:<head>and<body>
<head>A node has two children:<meta>with<title>node<title>The node also has a child node: the text node "DOM tutorial"<h1>and<p>A node is a sibling node and is also<body>And:<head>The element is<html>Element's first child node<body>The element is<html>Last child node of the element<h1>The element is<body>Element's first child node<p>The element is<body>Last child node of the elementCopy the code

Js provides many ways to find an element node on a page

4.1 DOM Access

  • GetElementById: The element node object is obtained by the ID attribute

Example: Block form submission when the account is empty

<body>
<formaction="xxx" onsubmit="return login()">
<p>Account:<input id="username"/></p>
<p>Telephone:<input id="phone"/></p>
<p><button>The login</button></p>
</form>

<script>
function login()	{
var name=document.getElementById("username").value;
if(name	== ""){
alert("Account cannot be empty!");
return	false;	// Block form submission
}
return	true;	// Let the form be submitted
}
</script>
</body>
Copy the code
  • GetElementsByName: Gets the element node object set through the name attribute

Case study: Shopping cart full selection effect

<body>
<h2>My shopping cart</h2>
<table	border="1" cellspacing="0">
<tr>
<td><input type="checkbox" onchange="quan(this)" />select all</td>
<td>The name of the</td>
<td>The unit price</td>
</tr>
<tr>
<td><input type="checkbox" name="one" />1</td>
<td>Energy drinks. - Screaming</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>The steamed stuffed bun</td>
<td>1.5</td>
</tr>
</table>

<p>
<button>Submit orders</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 checkboxes to each checkbox}}</script>
</body>
Copy the code
  • GetElementsByTagName: Gets the element node object set by tag name

Case in point: Table discoloration on interlaced lines

<body>
<table border="1" cellspacing="0">
<tr>
<td><input type="checkbox" onchange="quan(this)" />select all</td>
<td>The name of the</td>
<td>The unit price</td>
</tr>
<tr>
<td><input type="checkbox" name="one" />1</td>
<td>Energy drinks. - Screaming</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>The steamed stuffed bun</td>
<td>1.5</td>
</table>


<script>
var rows=document.getElementsByTagName("tr");	// Get the collection of element objects by the tag name
for(var i=0; i<rows.length; i++) {if(i%2= =1) {/ / odd
rows[i].style.backgroundColor="pink"; }}</script>
</body>
Copy the code

4.2 DOM modification

Modifying HTMLDOM can mean many different things:

  • Changing HTML content
  • Changing CSS styles
  • Changing HTML attributes
  • Create a new HTML element
  • Delete existing HTML elements
  • Change the event (handler)
  • 1. Change the HTML content of an H2 element
<body>
<button	onclick="test()">Let me try</button>

<script>
function test(){
document.getElementById("hello").innerHTML="Go, drink some ~!";
}
</script>

<h2 id="hello">Hello!</h2>
</body>
Copy the code
  • Change the HTML style of a H2
<body>
<button	onclick="chou()">You see what</button>
<script>
function chou(){
document.getElementById("hello").style.color="red";
document.getElementById("hello").style.fontFamily="Chinese Colorful Clouds";
}
</script>
<h2 id="hello">Hello!</h2>
</body>
Copy the code

4.2.1. Adding a Node

Click the button to create an image on the page

<body>
<button	onclick="add()">add</button>
<div></div>

<script>
function add(){
var	img=document.createElement("img");//	<img>	
img.setAttribute("src".".. /111-html/img/cat.gif");//

img.setAttribute("title"."Kitty");	// 

img.setAttribute("id"."cat");	// 

var	divs=document.getElementsByTagName("div");
divs[0].appendChild(img);
}
</script>
</body>
Copy the code

4.2.2 Deleting a Node

Click the button to delete the image you just created from the page

<body>
<button	onclick="add()">add</button>
<button	onclick="del()">delete</button>
<div>
</div>

<script>
function add(){... A little... }function del(){
var	img=document.getElementById("cat");
img.parentNode.removeChild(img);// You must pass the parent node to delete the child node
}
</script>
</body>
Copy the code

4.2.3. Replace a Node

Click the button to replace the image you just created with another one

<body>
<button	onclick="add()">add</button>
<button	onclick="del()">delete</button>
<button	onclick="rep()">replace</button>
<div>
</div>

<script>
function	add(){... A little... }function	del(){... A little... }function	rep(){
var	imgold=document.getElementById("cat");
// Make the substitution by modifying the attributes of the element
// 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>
Copy the code

4.3, events,

Js captures feedback from an action

  • Examples of HTML events:
  • When the user clicks the mouse
  • When the page is loaded
  • When the image is loaded
  • When the mouse moves over the element
  • When an input field is changed
  • When an HTML form is submitted
  • When the user triggers the button

4.3.1 WindowEvents

Only valid for the 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>
Copy the code

4.3.2 Form Element Events

Only valid within form elements.

  • Onblur Executes the script when an element loses focus
  • Onfocus Executes the script when the element gets focus
<body>
<script>
function a(){
console.log("Gain focus == be activated");
}
function b(){
console.log("Out of focus");
}
</script>

<formaction="">
<p>Account:<input onfocus="a()" onblur="b()"/></p>
<p>Password:<input/></p>
</form>
</body>
Copy the code

4.3.3 MouseEvents

  • Onclick Executes the script when the mouse is clicked
  • Ondblclick Executes the script when the mouse is double-clicked
  • Onmouseout Executes the 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("Clicked.");
}

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

function shang(img){
img.style.border="5px	solid	red";
}
function xia(img){
img.style.border="5px	solid	white";
}
</script>
</body>
Copy the code

4.3.4 keyboard events

  • Press onkeydown
  • Onkeyup flare up
<script>
window.onkeydown=function(){
// event: event source (button)
// console.log(" keyCode: "+ event.keycode);
if(event.keyCode=="13") {/ / enter key
alert("Login successful!"); }}window.onkeyup=function(){
console.log(event.keyCode);	// Holding the button down will not trigger it. When released, the key bounces back to trigger
}
</script>
Copy the code

4.3.5. Event bubbling

Create two divs, one large and one small

<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, it is important to know that this event happened, 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("Events for child elements are triggered:"+this.id);
});
</script>
</body>
Copy the code

The son comes before the father. The order in which events are emitted * * is called event bubbling;

4.3.6 Event capture

Again, create two divs, one bigger 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>
document.getElementById("father").addEventListener("click".function(){
alert("Parent:"+this.id);
},true);
document.getElementById("child").addEventListener("click".function(){
alert("Sub-level:"+this.id);
},true);
</script>
</body>
Copy the code

Father, son. The event firing sequence is changed to, that’s event capture;

4.4 object Oriented OOP

Create a generic Object with Object


var	user=new	Object(a); user.name="吕布";
user.age=21;
user.say=function(){
console.log("Hello everyone, my name is:"+this.name+"This is my year."+this.age+"Age!);
}
user.say();
var	dog=new	Object(a); dog.nickname="A lot of shit and urine.";
dog.wang=function(){
console.log("I'm hungry. I'm going to tear down my house!");
}

dog.wang();
Copy the code

Using constructors

function userinfo(name,age){
this.name=name;
this.age=age;
this.say=function(){
console.log("Hello everyone, my name is:"+this.name+"This is my year."+this.age+"Age!); }}var user=new userinfo("James".35);
user.say();
Copy the code

Use direct quantity

var user={
username:"Sun Wukong".age:527.say:function(){
console.log("Hello everyone, my name is:"+this.username+"This is my year."+this.age+"Age!); }}; user.say();Copy the code

4.5, JSON

People are sending data back and forth across the Internet, and without a common format, it can be very difficult to parse (everyone has different coding preferences)

JSON(JavaScriptObjectNotation) is a lightweight data interchange format.

Easy for humans to read and write, but also easy for machines to parse and generate

{attribute 1: value 1, attribute 2: value 2,… }

<script>
var	json1={username:"吕布".age:31	};
console.log("Name:"+json1.username+", age:+json1.age+"Age");
/ / the json array
var	josnarr	=[{name:"The sable cicada".age:18}, {name:	"Joe".age:17}];
console.log("The sable cicada"+josnarr[0].age+"Old");
console.log("Joe"+josnarr[1].age+"Old");
// Complex JSON objects
var	long={
name:"Zhaoyun".sex:"Male".hobby: ["Jade white Dragon Pony"."Gentian Silver Spear"."Green Y-Sword"]};console.log(long.name+"Main weapon of attack:"+long.hobby[1]);
</script>
Copy the code

2. BOM operation

It’s the way javascript does some general things to the browser

2.1. Window objects

<button	onclick="kai()">Speed induction</button>

<script>
function	kai(){
window.open("http://lagou.com"	,"111"."width=500,height=300,left=400");
// window.open("http://lagou.com" ,"111", "fullscreen=yes"); / / IE onlyEffective}</script>
Copy the code

5.1.1 screen Objects

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

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

5.1.2 Location Location

Contains information about the current URL, usually used to jump to the page

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

5.1.3, history Browser history

The history object records traces of the browser

A.html <ahref="b.html"</a>

b.html

<button	onclick="hui()">return</button>

<script>
function	hui(){
//history.go(-1); // Upper page
history.back();	// Is equivalent to go(-1)
}
</script>
Copy the code

5.1.4 Navigator Navigation

The window.navigator object contains information about the visitor’s browser;

<script>
var	str="";
str+="

Browser code:"

+ navigator.appCodeName +"</p>"; str+="

Name of browser:"

+ navigator.appName+"</p>"; str +="

Browser version:"

+ navigator.appVersion+"</p>"; str+="

Hardware platform:"

+ navigator.platform+"</p>"; str+="

User agent:"

+ navigator.userAgent +"</p>"; str+="

Enable Cookies:"

+navigator.cookieEnabled+"</p>"; document.write(str);
</script> Copy the code

5.1.5. Store Objects

It is very similar to map in Java, which stores data in key-value pairs

5.1.5.1 localStorage localStorage

This data is deleted after closing a window or TAB

Save the data

localStorage.setItem("name"."curry");
Copy the code

Extract the data

localStorage.getItem("name");
Copy the code

Delete the data

localStorage.removeItem("name");
Copy the code

Diversified operation

// There are three ways to save data
localStorage["a"] =1;
localStorage.b=2;
localStorage.setItem("c".3);

// Check the data type
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 to read
var	b=localStorage["b"];
console.log(b);

// The third way to read
var	c=localStorage.getItem("c");
console.log(c);
Copy the code

5.1.5.2 sessionStorage sessionStorage

A session is to keep the browser open.

Closing browsing is the end of a session.

Opening a browser means creating a session.

Save the data

sessionStorage.setItem("name"."klay");
Copy the code

Extract the data

var	lastname=sessionStorage.getItem("name");
Copy the code

Deletes data for the specified key

sessionStorage.removeItem("name");
Copy the code

Delete all data

sessionStorage.clear();
Copy the code

Example: Record how many times a button is clicked

<button	onclick="dian()">Am I</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") +"Time!"
}
</script>
Copy the code

5.2 timing operation

5.2.1. Periodic timer setInterval

SetInterval (1,2) : periodically triggers code exp

  • 1: execute the statement
  • 2: indicates the time period, in milliseconds

Example: Blinking font (1 color change in 1 second)

<body>
<h1	id="title">Pull hook net: speed 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 start again}}setInterval(bian,100);	// Execute the bian function every 0.1 seconds
</script>
</body>
Copy the code

Case study: Based on flicker font extension, flicker electronic clock

<body>
<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; }} function time(){var d=new Date(); Var STR = d.g etFullYear () + "years" + (d.g etMonth () + 1) + "month" + d.g etDate () +" "+ d.g etHours () +" "+ d.g etMinutes () +" points "+ d.g etSeconds () +" s "; document.getElementById("title").innerHTML=str; } setInterval(bian,100); Bian setInterval(time,1000); // Execute the time function every 1 second</script>
</body>
Copy the code

5.2.2. Stop the timer clearInterval

Case study: Mock annual raffle

<body>
<img	id="tu"	src=".. /lagou-html/img/1.jpg"	width="50%"	/>
<br	/>
<button	onclick="begin()">start</button>
<button	onclick="stop()">stop</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 global
}

functionstop()	{
clearInterval(timer);// Stop the timer
}

function bian()	{
var	i=Math.floor(Math.random()*	arr.length);/ / 0 to 4
document.getElementById("tu").src=".. /111-html/img/"+arr[i];
}
</script>
</body>
Copy the code

5.2.3 One-time timer setTimeout

The effect is equivalent to delay and is executed only once

<script>
functionbian(){
document.body.style.backgroundColor="red";
}


// call after 3 seconds
setTimeout(bian,3000);
</script>
Copy the code