1, Composition of JavaScript
-
ECMAScript: (core) specifies the Js syntax and basic objects
-
DOM: method and interface of document object model to process web page content markup document html operation document elements
-
BOM: browser objects, manipulating browsers
2, Introduction of JavaScript
- Internal script mode
<script type = "text/javascript"> //type can be omitted //Js script content is executed from top to bottom </scrpit> <!-- In theory, it can be placed anywhere-->
- Placed in an external file, any html can be referenced
<script type = "text/javascript" src = "js route"> //It doesn't write code and can't execute </script>
3, Syntax specification of JavaScript
1. Notes
-
Single line note://
-
Multiline comment:/**/
2. Variables
1. Declaration of variables:
var variable name; (unassigned default is undefined)
2. Declaration and assignment of variables
var variable name = value;
3. Type of variable:
1. Basic data type:
- String: both string types' 'and' 'represent strings
- boolean: boolean type true false
- Number: any number of number type
- null: empty placeholder
- Undefined: undefined type has only one fixed value undefined
Because JavaScript is a weakly typed language, you can't see the variable type at once. You can judge the variable type with the typeof operator
var str = 1; str = true; str = null; // A variable can be assigned any type as long as it is declared
The typeof operator can be used to determine the type of a variable typeof(str), but there is a bug typeof(null) == object
2. Reference data type:
It is usually called class, but javascript has no compilation process, so there is no concept of class
Flag creation method:
var str = new String();
var str = new String; js unique
3. Operator
1. Comparison operator:
-
===(compare specific values and types) str1 = 10; str2 = “10”; Result false
-
==(compare specific values) str1 = 10; str2 = “10”; Result true
Everything else is the same as Java
2. Logical operators: & & (and) | (or)! (non)
4. Regular objects
1. Creation method of reqexp object
var reg = new RegExp("expression"); //Not used for basic development var reg = /^expression $/ //Direct quantity (commonly used in development) // ^The beginning $and the end are regular objects
2. ReqExp object method
Test (string)// If all characters of the string conform to the regular expression, return true; otherwise, false
3. Precautions for using regular objects
/^The expression $/ is false if only one character does not match. Only if all characters match is true (used for form verification)
/Expression / as long as one character matches, it is true, and all matches are false
5. JS array object
1. Characteristics of JS array: JS array can see the ArrayList collection in Java
There is no limit on the type of each member in the array, and the length of the array can be modified arbitrarily
2. Four creation methods of JS array
-
var arr = [1,2,3,“a”,true]; // Common JS arrays
-
var arr = new Array(); // Create JS array. The default length is 0 1 2
-
var arr = new Array(); // Create JS array. The default length is 4
-
var arr = new Array(“1”,ture); // Create JS array initialization
3. Common properties / methods of JS array
-
Attribute: length: array length
-
method:
-
join(string): each element of the array can be connected according to the character given by string. Each array element has no effect on the original array
-
reverse(): inverts the array elements
-
push(): adds an element to the end of the array and returns a new length
-
pop(): deletes and returns the last element of the array
6. Global function
1. Implementation
eval(string) function: execute the passed string as script code. This string can only be a basic data type string. String can also convert JSON string into an object
2. Encoding and decoding
URL/URI Code: Chinese and special symbols hexadecimal
Function: ensure the integrity of data transmission
-
encodeURI(string) encodes the string to the tail URI
-
decodeURI(string) decodes an encoded URI
3. Difference between URI and URL
URL: unified resource locator (including http: / /) to locate the location of network resources
URI: uniform resource identifier (including resource name), identifying the detailed network name
For example:
- http://www.lzjer.com/ Is URL
- index.html is a URI
- http://www.lzjer.com/index/html Both URL and URI
4. String to number
1 parseInt(string) parses a string and returns an integer (the decimal part is directly discarded)
2 parseFloat(string) parses a string and returns a floating-point number (if you encounter a number that cannot be parsed, stop parseFloat("11.5a5") = = 11.5
Note: if the first digit is not qualified, Nan (not a number) is returned directly
NAN is a digital ID, not a number
7. User defined functions
1. Format of function:
function method name (parameter list){
Function body;
}
be careful:
- The parameter definition does not need the var keyword and can be used directly
- For the function body of javascript, return can be written or not. You can write the value of return or return;
- The return value without writing return is undefined
For example:
function getSum(a,b){ return a + b; }
2. Precautions for user-defined functions
- There are no overloads in javascript, only method overrides, and the last defined function with the same name will override the previous function
- Since the formal parameters of the real participating function do not match, it does not affect the normal use
- If the formal parameter is assigned, the default undefined is used
8. Custom objects
1. Use function function to create object
Parameterless format
function object name (){
Function body;
}
example:
//Declared an object function Person(){ } //The Person object was created var p = new Person(); alert(p); //appear [object Object] Created successfully
this represents the current class object Person
function Person(){ this.name = "Xiao Fang"; this,age = 18; } var p = new Person(); alert(p.name); alert(p.age);
How to assign values to attributes
//1. Assignment of construction parameters function Person(a,b){ this.age = a; this.name = b; } var p = new Person(17,"Xiao Fang"); //2. Attribute assignment of calling object function Person(a,b){ this.age = a; this.name = b; } var p = new Person(17,"Xiao Fang"); p.name = "petty thief";
2. Direct quantity of object (Json form)
Format: var object name = {attribute name 1: "attribute value 1", attribute name 2, "attribute value 2",...}; the object is created directly, and the new object is not required
Create initialization properties and property values
var p = {name:"Xiao Fang", age:12}; alert(p.name + "-------" + p.age) p.name = "Xiao Wang"; alert(p.name);
4, BOM object
1. What are BOM objects and what are their functions
BOM(Browser Object Model)
Function: used to perform browser related operations (e.g. browser address bar, pop-up message)
In general, window represents the BOM object
Note: windo object is a built-in object of Javascript. When it is applicable to calling methods and properties of window object, window can be omitted
(for example, alert() is a window method, but it is written directly to alert())
β
2. Message box
-
alert(); warning box pops up
-
boolbean confirm(); confirmation box (display OK cancel)
There is a return value. When the point is determined, return true and cancel return false
var b = confirm("Hello"); alert(b);
3. Timer
1. Setting and cancellation of cycle timer
1. Start cycle timer:
setInterval("call method", millisecond value); call the parameter (method) every millisecond, and the return value is an id) (usually remind the user what to do)
function run1(){ alert("run1"); } setInterval("run1()", 2000);
2. Cancel the cycle timer
Clearinterval (ID of the cycle timer);
function run1(){ alert("run1"); } var id = setInterval("run1()", 2000); clearInterval(id);
β
β
2. Setting and cancellation of primary timer
1. Start the one-time timer
setTimeout("call method", milliseconds); The return value is an id and is only reminded once
2. Cancel the timer once:
clearTimeout(id);
function run1(){ alert("run1"); } //Start the timer once var id = setTimeout("run1()", 2000); //Stop one time timer clearTimeout(id);
β
4. location object
1. Properties of location object:
- href / / the full URL of the current browser address bar
var url = location.href; //Get current URL location.href = ""; //Modify URL
Small demand: jump to Baidu in two seconds
function run(){ location.href = "http://www.baidu.com"; // You must write http:// } setTimeout("run()",2000);
5, DOM object
1. What are DOM objects and what are their functions?
DOM(Document Object Model) document object model
DOM encapsulates all contents (labels, text, attributes) in a markup document into objects
Control or change the HTML display effect (special effect) by operating the properties or methods of DOM objects
2. Introduction to DOM tree
<html> <head> <title> document title</title> </head> <body> <a href = "">My link</a> <h1>My title</h1> </body> </html>
The above HTML documents are parsed by the browser from top to bottom and loaded into the browser memory
Of which:
- Each tag is loaded as an element node object on the DOM tree
- The attributes of each tag are loaded as an attribute node object in the DOM tree
- The content of each tag is loaded as a text node object on the DOM tree
- The whole DOM tree is a document node object, that is, a DOM object
- When an HTML document is loaded into memory, it forms a DOM object
DOM tree features:
- Each node is a node object
- Common node relationships: parent-child node relationships
- The text node object has no child nodes (it is itself a leaf node)
- Every node has a parent node (except the root node)
3. Get element node object
DOM object document
Four methods to get element node objects
-
getElementById() gets the object by id. if it is not found, null is returned
-
getElementByName() gets all matching element objects through name
Return object array not found return empty -
getElementByTagName() gets all matching objects through the element tag name
Returns an array object -
getElementByClassName() gets all matching objects through the element name class attribute
Returns an array objectbe careful:
The node object obtained here should be placed at the bottom to prevent the front label from being loaded into the browser
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Get element node object</title> </head> <body> <input type="button" id = "iid" class="kike" name="kk"/> <input type="text" id = "lzj" class="kike" value="rich"/> <input type="button" id = "sm" /> <input type="button" id = "kkk" name="kk"/> <ui> <li>lzj</li> <li> </li> </ui> <script> var v = document.getElementById("lzj"); alert(v); var arr = document.getElementsByClassName("kike"); alert(arr.length); var arr1 = document.getElementsByName("kk"); alert(arr1); var arr2 = document.getElementsByTagName("li"); alert(arr2.length); </script> </body> </html>
4. Common attribute values of element objects
-
value
Element object. Value gets the value of the value attribute of the element object
Element object. Value = attribute value changes the attribute value of element object -
className
Element object. className gets the class attribute of the element object
Element object. className = attribute value sets the class attribute value of the object
<!DOCTYPE html> <html lang="en"> <head> <title>Element object common attributes</title> </head> <body> <input type="text" id="t1" value="Hello" class="kkk"/> <script> var d = document.getElementById("t1"); alert(d.value +"----"+ d.id + "----"+d.type +"-----"+d.className); </script> </body> </html>
- checked
Element object. Checked gets the checked attribute value of the element object
Element object. Checked sets the checked attribute value of the element object
The property value of checked is true π false, which indicates whether the radio box | check box is selected
<!DOCTYPE html> <html lang="en"> <head> <title>Element object common attributes</title> </head> <body> <input type="checkbox" id="hobby" /> <script> var c=document.getElementById("hobby"); alert(c.checked); c.checked=true; </script> </body> </html>
- innerHTML
The element object. InnerHTML gets the innerHTML attribute value of the element object, which is the text content
Element object. InnerHTML = "attribute value" sets the innerHTML attribute value of the element object
<!DOCTYPE html> <html lang="en"> <head> <title>Element object common attributes</title> </head> <body> <span id="s1">What a nice day today</span> <script> var s = document.getElementById("s1"); alert(s.innerHTML); s.innerHTML+= "οΌYes, it's sunny"; </script> </body> </html>
6, JS event
1. What is JS event and what is its function
Usually, the action of mouse or hotkey is called event
Click, form submission, value change, mouse in and mouse out
Through JS events, we can complete the special effects specified on the page
2. JS event driven mechanism
For the special effects on the page, we can understand the following in the JS event driven mechanism
JS event driven mechanism:
Event source:
event:
monitor:
Register listener:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Event driven mechanism</title> <script> function run(){ alert("run"); } </script> </head> <body> <input type="button" id="click" onclick="run()" value="Point me"/> </body> </html>
Event source: button
Event: click event onclick
Listener: run() method
Register listener: ο nclick=“run()”
3. Common JS events
1. Click event
ο nclick = "need to execute method" to bind the method. Click to trigger the execution of the function
2. Focus events
Focus events:
onfoucus = "need to execute method" bind method click a place to get focus
Loss of focus event: ο nblur = "method needs to be executed" the binding method originally points to a certain place. When the mouse is not clicked, click other places to lose focus
3. Domain content change event
ο nchange = "method needs to be executed" when the value changes, the bound method will be executed
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function run(){ alert("The value has changed"); } </script> </head> <body> <select onchange="run()"> <option>Beijing</option> <option>Shanghai</option> <option>Nanjing</option> </select> </body> </html>
4. Loading completion event (multi use)
ο nl ο ad = "method needs to be executed" trigger the release of binding after loading
For example, a pop-up window will pop up after the body is loaded
<script> function run(){ alert("eject"); } <script> <body onload="run()"> </body>
5. Form submission event (generally used for form verification)
ο nsubmit = "execution method required" the binding method is triggered after the form is submitted
If you want to get the return value ο nsubmit = "return" the method needs to be executed; if ο nsubmit=true; allow form submission. If false, prevent submission
6. Key position pop-up event
ο nkeyup = "need to execute method"
7. Mouse events
Mouse in event: ο nm ο use ο ver = "method needs to be executed"; the binding method will be triggered as long as the mouse moves into the bound component
Mouse out event: ο nm ο use ο ut = "need to execute method" as long as the mouse overflows, the binding component triggers the binding method
4. JS events are bound in two ways
1. Event handle binding:
The event is written inside the tag in the form of attribute, and then the corresponding function is bound
Bind a method
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function run(){ alert("Hello?"); } function run1(a ){ alert(a); } function run2(obj){ alert(obj.value); } </script> </head> <body> <!-- Nonparametric method --> <input type="text" value="1111" onclick="run()"><br> <!-- Parametric method --> <input type="text" name="1111" id="1111" onclick="run1('Hello')"><br> <!-- Parametric method parameters are objects this Represents this label element object --> <input type="text" value="12345" onclick="run2(this)"><br> </body> </html>
Bind multiple methods
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function run(){ alert("Hello?"); } function run1(){ alert("aka"); } function run2(){ alert("skr"); } </script> </head> <body> <!-- The order of execution is the order of binding --> <input type="text" value="1111" onclick="run(),run1(),run2()"><br> </body> </html>
Advantages and disadvantages of event handle binding method:
advantage:
1. Fast development
2. Convenient transmission
3. Multiple functions can be bound
Disadvantages: JS and HTML codes are highly integrated, which is not conducive to the maintenance of departmental projects (too much coupling)
2. DOM binding method: use the corresponding properties of DOM to bind events
Format:
DOM object. JS event = method name; (only one method can be bound at a time)
//Recommended use
DOM object. JS event = function(){
Method 1 ();
Method 2 ();
}
(bind anonymous methods, you can bind multiple method functions, which is equivalent to anonymous internal classes in Java, recommended)
//Called when the page is loaded window.onload=function(){ run1(); run2(); run3(); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> function run1(){ alert("run1"); } function run2(){ alert("run2"); } //Since the pages are executed sequentially, only the node element object is obtained through the id after the page is loaded window.onload=function(){ var t1=document.getElementById("t1"); t1.onclick=function(){ run1(); run2(); } } </script> </head> <body> <!-- Is a text box onclick Event binding two functions run1() run2() --> <input type="text" id="t1"> </body> </html>
Advantages and disadvantages of DOM binding
Advantages: separation of HTML and JS code
Disadvantages: parameters cannot be passed (resolved = function(a) {} through anonymous functions)
Only one method can be bound at a time (resolved through anonymous functions)