JS Basics

Posted by spudmclard on Sat, 18 Dec 2021 08:58:17 +0100

JS

brief introduction

characteristic

  • Interpretative language
  • Syntax structure similar to C and Java
  • Dynamic language
  • Prototype based object oriented

Basic grammar

Output statement

    <script type="text/javascript">
        // Control the browser to pop up a warning box
        alert("This is my first line js code")
        // Let the computer output a content in the page and write a content in the Body
        document.write("123")
        // Output a content to the console
        console.log("console output ")
    </script>

position

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 
        Can js Code to external js File, and then through script Label introduction
        Writing to an external file can be referenced in different pages at the same time, or the browser's cache mechanism can be used
     -->
     <!-- 
         script Once the tag is used to import an external file, you can no longer write code. Even if you write a browser, it will be ignored
         If necessary, you can create a new one script Tags are used to write internal code
      -->
    <script type="text/javascript" src="js/script.js"></script>
</head>
<body>
    <!-- 
        Can JS Code to label onclick Properties, when we click the button, js Code will execute
        Although they can be written in tag attributes, they belong to structure and behavior coupling, which is inconvenient for maintenance and is not recommended 
    -->
    <button onclick="alert('123')">Click on me</button>

    <!-- Can js The code is written in the of the hyperlink href Property so that when a hyperlink is clicked, the js code-->
    <a href="javascript:alert('321')">Point link</a></a>
</body>

characteristic

1. Strictly case sensitive

2. Every statement in JS ends with a semicolon. If you don't write a semicolon, the browser will automatically add it, but it will consume some resources, and sometimes the browser will add a wrong semicolon, so the semicolon must be written in development

3. JS ignores multiple spaces and line breaks. So you can format the code with spaces and newlines

Declare variable

Use the var keyword to declare a variable

data type

A data type is a literal type

There are six data types in JS

String string Number numeric Boolean Boolean Null null Undefined undefined Object object not defined

Except that Object belongs to the reference data type, others belong to the basic data type

String

String string:

  • In JS, strings need to be enclosed in quotation marks
  • Double quotation marks or single quotation marks can be used, but don't mix them
  • Quotation marks cannot be nested, double quotation marks cannot be placed inside double quotation marks, and single quotation marks cannot be placed inside single quotation marks

In the string, we can use \ to represent the escape character. When it represents some special symbols, we can use \ to escape

Number

In JS, all values are of type Number, including integers and floating-point numbers

The typeof variable can check the type of a variable

If the Number represented by Number exceeds the maximum value, an Infinity is returned indicating positive Infinity

NaN is a special number, indicating Not A Number. Using typeof to check a NaN will also return number

The operation of integers in JS can basically ensure accuracy, but the calculation of floating-point numbers may get an inaccurate result, so do not use js for operations requiring high accuracy

Boolean

Null and Undefined

The null value is specifically used to represent an empty object. When using typeof to check a null value, object will be returned

There is only one value of undefined type, which is undefined. When a variable is declared but no value is assigned to the variable, its value is undefined. When using typeof to check an undefined value, an undefined value is returned

Force conversion

Convert to String

Method 1: call the toString() method of the converted data type. This method will not affect the original variable. It will return the conversion result. However, note: there is no toString method for null and undefined values. If you call it, an error will be reported

Method 2: call the String() function and pass the converted data to the function as parameters. For Number and Boolean, it is actually the toString() method called, but for null and undefined, toString() method will not be called. It will convert null and undefined into strings

Convert to Number

Method 1: use the Number() function:

  • String to number

If it is a pure numeric string, it is directly converted to a number

If there is non numeric content in the string, it is converted to NaN

If the string is an empty string or a string full of spaces, it is converted to 0

  • Convert Boolean to number

true to 1

false to 0

  • Convert Null to number

0

  • undefined to number

NaN

Method 2: this method is specifically applicable to strings

parseInt() converts a string into an integer, which can take out the valid integer content in the string and convert it into Number

parseFloat() converts a string to a floating-point number. The function is the same as above

Convert to Boolean

Using the Boolean() function

  • Convert numbers to Boolean

All are true except 0 and NaN

  • Convert string to Boolean

All are true except empty string

  • Both null and undefined are converted to false
  • Object is also converted to true

Other hexadecimal digits

Indicates hexadecimal, starting with 0x, indicating octal, starting with 0, indicating binary 0b

Strings like 070 can be parsed as octal in some browsers and as hexadecimal in others

object

Object Literal

//Create an object
var obj = new Object();
//Use object literals to create an object
obj = {};

Using object literals, you can directly specify the properties in the object when creating the object,

Syntax: {property name: property value, property name: property value...}

Object literal attribute names can be quoted or not. It is recommended not to. If you want to use some special names, you must use quotation marks

this

// The parser passes an implicit parameter to the function every time it calls the function
// The implicit parameter is this. This points to an object
// This object is called the context object of function execution
// this will point to different objects depending on the calling method of the function
// 		1. Call in the form of function. this is always window
// 		2. Call in the form of method. this is the object that calls the method
//      3. Call in the form of constructor. This is the newly created object
function fun(){
    console.log(this.name);
}

// Create an object
var obj = {
    name:"zzh",
    sayName:fun
};

//Method call
obj,sayName();
//The function call is equivalent to window fun()
fun();

Supplement:

var name = "overall situation";

//Create a fun() function
function fun(){
	console.log(this.name)
}

//Create two objects
var obj = {
	name:"zzh",
    sayName:fun
}

var obj2 = {
	name:"gj",
    sayName:fun
}

//Call with obj
obj.sayName();
//Call with obj2
obj2.sayName();

Create objects using factory methods

function createPerson(name, age, gender){
	//Create a new object
	var obj = new Object();
	
	//Adding attributes to an object
	obj.name = name;
    obj.age = age;
    obj.gender = gender;
    obj.sayName = function(){
        alert(this.name);
    }
    //Latest object discovery
    return obj;
}

var obj2 = createPerson("zzh",30,"male");

For objects created using factory methods, the constructor used is Object, so the objects created are of type Object, which makes it impossible for us to distinguish many different types of objects

Constructor

Create a constructor specially used to create a Person object. The constructor is an ordinary function. The creation method is no different from that of ordinary functions. The difference is that the constructor is used to capitalize the first letter

The difference between constructors and ordinary functions is that they are called in different ways. Ordinary functions are called directly, and constructors need to use the new keyword

Execution process of constructor:

1. Create a new object now

2. Set the newly created object as this in the function. You can use this in the constructor to reference the newly created object

3. Execute the code in the function line by line

4. Returns the newly created object as a return value

Use instanceof to check whether an object is an instance of a class

An object created with the same constructor is called a class object, and a constructor is also called a class. The object we will create through a constructor is called an instance of the class

prototype

For each function we create, the parser will add an attribute prototype to the function

This attribute corresponds to an object, which is what we call the prototype object

If a function calls prototype as an ordinary function, it has no effect. When a function is called in the form of a constructor, the object it creates will have an implicit attribute pointing to the prototype object of the constructor. We can__ proto __ To locate this attribute

The prototype object is equivalent to a public area. All instances of the same class can access the prototype object. We can uniformly set the common contents of the object into the prototype object

When we access a property or method of an object, it will first look for it in the object itself. If there is one, it will be used directly. If there is no one, it will look for it in the prototype object. If it is found, it will be used directly

Later, when we create constructors, we can uniformly add the properties and methods shared by these objects to the prototype object of the function, so that each object can have these properties and methods without adding them separately for each object and affecting the global scope

function MyClass(){

}
//Add attribute a to the prototype of Myclass
MyClass.prototype.a = 123;

var mc = new MyClass();
//console.log(MyClass.prototype);
//console.log(mc.__proto__);
console.log(mc.a);

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-u67gc3jv-1630464238500) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210829173704345. PNG)]

Prototype object

The prototype object is also an object, so it also has a prototype

When we use the properties or methods of an Object, we will first look for them in ourselves. If there are any in ourselves, we will use them directly. If not, search in the prototype Object. If there is in the prototype Object, use. If not, search the prototype of the prototype until the prototype of the Object object is found

The prototype of the Object object has no prototype. If it is still not found in the Object, it returns undefined

function MyClass(){

}
//Add a name attribute to the prototype of MyClass
MyClass.prototype.name = "Name in prototype";

var mc = new MyClass();
mc.age = 18

console.log(mc.name);

//When using in to check whether an object contains a property, if it does not exist in the object but exists in the prototype, it will also return true
console.log("name" in mc);

//You can use the object's hasOwnProperty() to check whether the object itself contains the property
//Using this method, true will be returned only if the object itself contains properties
console.log(mc.hasOwnProperty("age"));//true

console.log(mc.hasOwnProperty("hasOwnProperty"));//false

console.log(mc.__proto__.hasOwnProperty("hasOwnProperty"));//false

console.log(mc.__proto__.__proto__.hasOwnProperty("hasOwnProperty"));//true

toString

function Person(name, age, gender){
	this.name = name;
	this.age = age;
	this.gender = gender;
}

//Create a Person instance
var per = new Person("zzh",30,male);

//When we print an object directly on the page, it is actually the return value of the toString() method of the output object
//If we want to output the object without outputting [object], we can add a toString () method to the object
per.toString = function(){
    return "123";
};


var result = per.toString();
console.log(result);
//console.log(per.__protp__.__proto__,hasOwnProperty("toString"));
console.log(per);//123

garbage collection

When an object does not have any variables or attributes to reference it, we will never be able to operate the object. At this time, this object is garbage. Too many such objects will occupy a lot of memory space, causing the program to slow down. Therefore, this garbage must be cleaned up.

There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory. We don't need and can't garbage collection

What we need to do is set the object that is no longer used to null

function

call and apply

  • call() and apply() are both methods of function objects, which need to be called through function objects

  • When calling call() and apply() to a function, the function will be called to execute

  • When calling call() and apply(), you can specify an object as the first parameter. At this time, the object will become the this of the function execution

  • The call() method can pass arguments after the object in turn

  • The apply() method needs to encapsulate the arguments into an array and pass them uniformly

function fun(){
	alert(this.name);
}

var obj = {
	name:"obj",
	sayName.fucntion(){
        alert(this.name);
    }
}

var obj2 = {
	name:"obj2",
	sayName.fucntion(){
        alert(this.name);
    }
}

obj.sayName.apply(obj2);//obj2

arguments

When calling a function, the browser will pass two implicit parameters each time: the context object this of the function and the object arguments encapsulating the arguments

arguments is a class array object. It can also manipulate data through index or obtain length

When calling the function, the arguments we pass will be saved in arguments

Even if we do not define formal parameters, we can use arguments through argument, which is just troublesome. arguments[0] represents the first argument

There is an attribute callee, which corresponds to a function object, that is, the object of the function currently being pointed to

function fun(){
	console.log(arguments instanceof Array);
    console.log(Array.isArray(argument));
    console.log(arugument.length);//Length of argument
    console.log(argument[1]);
}

fun("hello", true);

Date

//Create a Date object
//If you directly use the constructor to create a Date object, it will be encapsulated as the execution time of the current code
var d = new Date();

//Create to spoof the specified time object
//You need to pass a string representing time as an argument in the constructor
var d2 = new Date("12/03/2016");

console.log(d2);

Packaging

Three wrapper classes are provided in JS, through which basic data types can be converted into objects

String() can convert the basic data type string to a string object

Number() can convert numbers of basic data types into number objects

Boolean() can convert Boolean values of basic data types to Boolean objects

However, we will not use basic data type objects in practical applications. If we use basic data type objects, some unpredictable results may be brought when making some comparisons

Methods and attributes can be added to objects, but not to basic data types. When we use the values of some basic data types to call properties and methods, the browser will temporarily use wrapper classes to convert them into objects, and then call the properties and methods of objects. After calling, convert it to the basic data type

var a = 123;

s = s.toString();

console.log(s); //123
console.log(typeof s); //string

regular expression

Regular expressions are used to define rules for some strings

//Objects to create regular expressions:

var variable = new RegExp("regular expression ","Matching pattern")

//The regular expression method test() is used to check whether a string conforms to the regular expression
//You can pass a matching pattern as the second parameter in the constructor:
//Can be i ignore case g global match pattern
                    
// Using literals to create regular expressions is simpler
// Using constructors to create more flexible                   
var reg = /a/i;                    

Use of regular expressions:

// |Represents or [] also represents or [A-z] any lowercase letter [A-z] any uppercase letter [A-z] any letter
// [^] except

Method of String object supporting regular expression

search retrieves the value that matches the regular expression

Match found a match for one or more regular expressions

replace replaces substrings that match the regular expression

split splits a string into an array of strings

regular expression syntax

Quantifiers can be used to set the number of times a content appears

var reg = /a{3}/; //a 3 times

reg = /ab{1,3}c/; //Limit b occurs 1 to 3 times

reg = /ab{3,}c/; //b more than 3 times

reg = /ab+c/; //At least one b

reg = /ab*c/; //0 or more

reg = /ab?c/; //0 or 1

req = /^a/; //Start with a

req = /a$/; //$means the end 

req = /^a|a$/; //Start with or end with a

Rules for mobile phone numbers:

1. Start with 1

2. The second digit is any number from 3 to 9

3. Any number after three digits: 9

req = /^1[3,9][0-9]{9}$/

In regular expressions, \ represents escape characters Represents any character

When using the constructor, because its parameter is a string and \ is the escape character in the string, if you want to use \, you need to use \ \

\w any letter, number_
\W except letters, numbers_
\d any number
\D except numbers
\s space
\S except spaces
\b word boundary
\B except word boundaries

//Remove spaces before and after the string
str = str.replace(/^\s*|\s*$/g, "");

Regular of mail

Any alphanumeric underline Any alphanumeric underline @ any alphanumeric Any letter (2-5 digits)

var emailReg = /^\w{3,}(\.\w+)@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;

DOM

The full name of DOM is Document Object Model

JS operates HTML documents through dom. As long as you understand DOM, you can operate the WEB interface at will

The document represents the whole HTML web page document. The object representation converts every part of the web page into an object, and uses the model to represent the relationship between objects, which is convenient for us to obtain objects

Node is the most basic part of our web page. Every part of the web page can be called a node, the label is called the element node, the attribute is called the attribute node, the text is called the text node, and the document is called the document node

Different types of nodes have different attributes and methods. [the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-w0db4wh6-1630464238503) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210830171947519. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ngvhxxp6-1630464238504) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210830171913971. PNG)]

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hap4sem2-1630464238507) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210830172048942. PNG)]

The browser has provided us with document nodes that can be used directly in the page. Document nodes represent the whole web page

<body>
    <button id="btn">
        This is a button
    </button>
    <script type="text/javascrpit">
    	//Get button object
		var btn = document.getElementById("btn");
		
		//Modify the text of the button
		btn.innerHTML = "modify";
    </script>
</body>

event

The interaction between JS and HTML is realized through events. We can set some JS codes in the properties corresponding to the event, so that these codes will be executed when the event is triggered

The event can be responded to in the form of a binding handler for the corresponding event of the button

In this way, when the event is triggered, its corresponding function will be called

//Get button object
var btn = document.getElementById("btn");

//Bind a click event
//A function bound to a click event like this is called a click response function
btn.onclick = function(){
    alert("123");
}

Loading of documents

When the browser loads a page, it loads it from top to bottom, and runs one line after reading it. If the script tag is written to the top of the page, the page has not been loaded when the code is executed

The purpose of writing js code to the bottom of the page is to execute js code after the page is loaded

The onload event can only be triggered after the entire page is loaded, and the corresponding response function of the event will be executed after the page is loaded, so as to ensure that all DOM objects have been loaded after our code execution

//Bind an onload event for window
window.oncload = function(){
	alert("hello");
}

DOM query

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wvvevyqx-1630464238508) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210830183954453. PNG)]

innerHTML is used to get the HTML code inside the element. For the self closing tag, this attribute has no meaning, such as input

If you need to read the element node attributes, use the element directly Attribute name and class attribute cannot be used in this way. Element is required to read class attribute className

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-mqphfe9j-1630464238510) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210830190243724. PNG)]

The childNode attribute above IE8 will include blank text, but not below IE8. Therefore, it is recommended to use the children attribute to obtain all child nodes of the current element and be compatible

firstChild also includes a blank text node. firstElementChild obtains the first child element of the current element (excluding a blank text node), but it does not support browsers of IE8 and below. If compatibility is required, try not to use it

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-femvbvs0-1630464238511) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210830191653832. PNG)]

There is an attribute body in the document, which holds the reference of body

//Get body tag
var body = document.body;

var html = document.documentElement;

//document.all represents all elements in the page
var all = document.all;

for(var i=0;i<all.length;i++){
    console.log(all[i]);
}

all = document.getElementByTagName("*");

//Query a group of element node objects according to the element class attribute
//getElementByClassName() gets a group of element node objects according to the class attribute value, but this method does not support IE8 and above
var box1 = document.getElementByClassName("box1");

//Get all div s in box1 with class
//querySelector() requires a selector string as a parameter. You can query an element node object according to a CSS selector
//IE8 can use querySelector() instead of getElementByClassName()
//Using this method will return a unique element. If there are multiple elements that meet the conditions, only the first one will be returned
document.querySelector(".box1 div");

document.querySelector(".box1");
console.log(div.innerHTML);

//Encapsulate all qualified elements into an array
//Even if there is only one eligible element, it will return an array
var box1 = document.querySelectorAll(".box1")

DOM addition, deletion and modification

document.createElement()

It can be used to create an element node object. It requires a label name as a parameter. The element node object will be created according to the label name and the created object will be returned as a return value

document.createTextNode()

It can be used to create a text node object. A text content is required as a parameter. A text node will be created according to the content and the new node will be returned

appendChild()

Adds a new child node to a parent node

insertBefore()

You can insert a new child node before the specified child node (called by the parent node)

repladeChild()

You can replace an existing child node with a specified child node

removeChild()

You can delete a child node. Child nodes parentNode can call the parent node

window.onload = function(){
    //Create a "Guangzhou" node and add it to the city
    myClick("btn01", function(){
        //Create Guangzhou node < li > Guangzhou < li >
        //Create li node
        var li = document.createElement("li");
        //Create a text node
        var gzText = document.createTextNode();
        li.appendChild(gzText);\
        //Get the node with id of city
        var city = document.getElementById("city");
        //Add Guangzhou under city
        city.appendChild(li);
    })
    //Another way to add Guangzhou nodes is recommended
    var li = document.createElement("li");
    //Set text to li
    li.innerHTML = "Guangzhou";
    //Add li to city
    city.appendChild(li);
}
function myClick(idStr, fun){
    var btn = document.getElementById(idStr);
    btn.onclick = fun;
}

for loop

The for loop is executed immediately after the page is loaded, and the response function is executed when the hyperlink is clicked. When the response function is executed, the for loop has already been executed

Action inline style

Modify the style of the element through js:

If the CSS style name contains - this name is illegal in JS, such as background color

You need to change the style name to the hump naming method, remove -, and then capitalize the letter after -

The styles we set through the style attribute are all inline styles, and inline styles have higher priority. All styles modified through JS tend to be implemented immediately

But if it's written in the style! Important, the style will have the highest priority at this time. The style cannot be overwritten even through JS. At this time, JS will fail to modify the style, so try not to add it to the style! important

The styles set and read through the style property are inline styles, and the styles in the style sheet cannot be read

window.onload = function(){
    //After clicking the button, modify the size of box1
    var box1 = document.getElementById("box1");
    //Click the response function for the button binding
    var btn01 = document.getElementById("btn01");
    btn01.onclick = function(){
        //Change the width of box1
        box1.style.width = "300px";
        box1.backgroundColor = "yellow";
    }
}

Read element style

Gets the current display style of the element

Element currentStyle. Style name

It can be used to read the displayed style of the current element. If the current element does not set the style, it will read its default value, but only IE browser supports it, and other browsers do not support it

In other browsers, you can use getComputeStyle() to get the current style of the element. This method is a window method and can be used directly

Two parameters are required. The first is the element to obtain the style, and the second is that a pseudo element can be passed, generally null

This method will return an object that encapsulates the style corresponding to the current element The style name is used to read the style. If the obtained style is not set, the real value will be obtained instead of the default value

However, this method does not support browsers of IE8 and below

Event object

Event object: when the response function of an event is triggered, the browser will pass an event object into the response function every time

All information related to the current event is encapsulated in the event object

onmousemove this event will be triggered when the mouse moves in the element

In IE8, when the response function is triggered, the browser will not pass the event object. In IE8 and below browsers, event objects are saved as properties of window objects

//When the mouse moves in areaDiv, the coordinates of the mouse are displayed in showMsg
var areaDiv = document.getElementById("areaDix");
var showMsg = document.getElementById("showMsg");

areaDiv.onmousemove = function(event){
    //clientX represents the x coordinate and clientY represents the y coordinate
    var x = event.clientX;
    var y = event.clientY;
    
    //Display mouse coordinates in showMsg
    showMsg.innerHTML = x + y;
}

Event Bubbling

Bubbling of events:

The so-called bubbling refers to the upward conduction of events. When an event on a descendant element is triggered, the same event of its ancestor element will also be triggered

In development, bubbling is useful in most cases. If you don't want event bubbling, you can cancel bubbling through the event object

event.cancelBubble = true

Delegation of events

Delegation of events

It refers to the unified binding of events to the common ancestor elements of elements, so that when the event on the descendant element is triggered, it will bubble to the ancestor element all the time, so as to process the event through the response function of the ancestor element

Event delegation takes advantage of bubbling, which can reduce the number of event bindings and improve the performance of the provider

//Binding an event only once can be applied to multiple elements, even if the element is added later
//You can try to bind it to the common ancestor element of the element
ul.onclick = function(event){
    event = event || window.event;
    
    //The target in target event represents the object that triggers the event
    if(event.target,className == "link"){
        alert("123");
    }
}

Event binding

Use object The method binding function of event = function can only bind one response function for one event of an element, not multiple. If multiple are bound, the latter will overwrite the former

Through this method, addEventListener() can also bind response functions for elements, and bind multiple response functions for the same event of an element at the same time. In this way, when the event is triggered, the response functions will be executed in the binding order of the functions

This method does not support IE8 and below browsers

Parameters:

1. The string of the event. Do not use on

2. Callback function, which will be called when the event is triggered

3. Whether to trigger an event in the capture phase requires a new Boolean value, which is generally passed as false

attachEvent()

In IE8, you can use attchEvent() to bind events. You can bind multiple functions for an event. The difference is that it is executed first after binding, and the execution order is opposite to that of addEventListener()

Parameters:

1. Event string, to on

2. Callback function

Define binding functions

//Defines a function that binds the response function to the specified element
//this in addEventListener() is the object that binds the event
//this in attachEvent() is window

//Parameter obj object to bind event string callback callback function of eventStr event
function bind(obj, eventStr, callback){
    if(obj.addEventListener){
        //Most browsers are compatible
    	obj.addEventListener(eventStr, callback, false);
    }else{
        //Who this is depends on how it is called
       	//callback.call(obj)
        //IE8 and below
        obj.attachEvent("on"+eventStr, function(){
            //call changes the object specified by This
            callback.call(obj)
        });
    }
    
}

Propagation of events

Netscape and Microsoft have different understandings about the spread of the event

Microsoft believes that events should be propagated from inside to outside, that is, when an event propagates, it should first trigger the event on the current element and then propagate to the ancestor element of the current element, that is, the event should be executed in the bubbling phase

Netscape believes that events are propagated from outside to inside, that is, when the current event is triggered, the event of the outermost ancestor element of the current element should be triggered first

W3C integrates the schemes of the two companies and divides the event communication into three stages:

1. Capture phase

In the capture phase, events are captured from the outermost ancestor element to the target element, but by default, events will not be triggered at this time

2. Target stage

The event is captured to the target element. After the capture, the event is triggered on the target element

3. Bubbling stage

Events are passed from the target element to its ancestor element, and events on the ancestor element are triggered in turn

If you want to trigger an event during the capture phase, you can set the third parameter of addEventListener() to true

The rest is skipped..

BOM

BOM is a browser object template. BOM enables us to operate the browser through JS. A group of objects are provided in BOM to complete the operation of the browser

BOM object:

  • Window represents the window of the whole browser. At the same time, window is also a global object in the web page
  • The Navigator represents the information of the current browser, which can be used to identify different browsers
  • Location represents the address bar information of the current browser. You can obtain the address bar information through location or operate the browser to jump to the page
  • History represents the history of the browser. The history of the browser can be operated through this object. Due to privacy problems, the object cannot obtain the specific history. It can only operate the browser to page forward or backward, and this operation can only be effective in the current access
  • Screen represents the screen information of the user, and the relevant information of the user's display can be obtained through this object

Navigator

Due to historical reasons, most properties in the Navigator object can no longer help us identify the browser. Generally, we only use the userAgent to judge the browser information

userAgent is a string that contains useful content to describe browser information. Different browsers will have different useragents

If you can't judge with userAgent, you can also judge the browser's information through some unique objects in the browser, such as activeobject

history

history.length() can get the number of currently accessed links

history.back() can be used to go back to the previous page, just like the browser's back button

history.forward() can jump to the next page, just like the browser's forward button

history.go() can be used to jump to the specified page. It requires an integer as a parameter. 1 means to jump forward to a page

Location

If you print location directly, you can get the information in the address bar (the full path of the current page)

If you directly change the location attribute to a complete path or relative path, our page will automatically jump to the path

assgin() is used to jump to other pages. Its function is the same as modifying location directly

reload() is used to update and load the current page. Its function is the same as that of the refresh button. If a true is passed in the method as a parameter, the cache will be forcibly emptied to refresh the page

replace() can replace the current page with a new page. After calling, it will jump to the page without generating a history. You cannot use the back button to back out

timer

setInterval() is called regularly. A function can be executed every other period of time

Parameters:

1. Callback function, which is called every other period of time

2. The event in milliseconds between each call

The return value is data of type Number, which is used as the unique identification of the timer

L ocation can obtain the address bar information or operate the browser to jump to the page

  • History represents the history of the browser. The history of the browser can be operated through this object. Due to privacy problems, the object cannot obtain the specific history. It can only operate the browser to page forward or backward, and this operation can only be effective in the current access
  • Screen represents the screen information of the user, and the relevant information of the user's display can be obtained through this object

Navigator

Due to historical reasons, most properties in the Navigator object can no longer help us identify the browser. Generally, we only use the userAgent to judge the browser information

userAgent is a string that contains useful content to describe browser information. Different browsers will have different useragents

If you can't judge with userAgent, you can also judge the browser's information through some unique objects in the browser, such as activeobject

history

history.length() can get the number of currently accessed links

history.back() can be used to go back to the previous page, just like the browser's back button

history.forward() can jump to the next page, just like the browser's forward button

history.go() can be used to jump to the specified page. It requires an integer as a parameter. 1 means to jump forward to a page

Location

If you print location directly, you can get the information in the address bar (the full path of the current page)

If you directly change the location attribute to a complete path or relative path, our page will automatically jump to the path

assgin() is used to jump to other pages. Its function is the same as modifying location directly

reload() is used to update and load the current page. Its function is the same as that of the refresh button. If a true is passed in the method as a parameter, the cache will be forcibly emptied to refresh the page

replace() can replace the current page with a new page. After calling, it will jump to the page without generating a history. You cannot use the back button to back out

timer

setInterval() is called regularly. A function can be executed every other period of time

Parameters:

1. Callback function, which is called every other period of time

2. The event in milliseconds between each call

The return value is data of type Number, which is used as the unique identification of the timer

clearInterval() can be used to close a timer. The method needs a timer ID as a parameter to close the corresponding timer

Topics: Javascript Front-end html5