Fifth, javaScript built-in objects and DOM manipulation
Complete JavaScript reference manual
There are three types of objects in JavaScript: built-in objects, browser objects, and custom objects.
1. JavaScript object definition and usage
Tutorial link: JavaScript object — W3school
How to create an object:
- Create objects in the original way;
- Factory mode creates objects;
- Custom constructors create objects;
- Create custom objects directly;
For example:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Document < / title > < script > / / 1. Var obj = new Object(); obj.name = "zhangsan"; // Add attribute obj. Age = 20; Obj. say = function(){console.log(this.name,":",this.age); } // Test console.log(obj.name); console.log(obj.age); Function createObject(name,age){var Object = new Object(); obj.name = name; // Add attribute obj. Age = age; Obj. say = function(){console.log(this.name,":",this.age); } return obj; } var ob1 = createObject("lisi",20); console.log(ob1.name); ob1.say(); var ob2 = createObject("wangwu",25); console.log(ob2.name); ob2.say(); console.log("============================="); Function Stu(name,age){this.name = name; this.age = age; this.say = function(){ console.log(this.name,":",this.age); Var s1 = new Stu("zhaoliu",28); var s2 = new Stu("xiaoli",21); s1.say() s2.say() console.log("============================="); Var ob = {name:"qq",age:26}; console.log(ob.name); console.log(ob.age); var obj={}; Obj. Name = "white"; Obj. say=function () {console.log(" my name: "+this.name); }; obj.say(); Var obj2={name:" ", age:20, say:function () {console.log(" "+this.name+"; Age: "+ this age); }}; obj2.say(); Var a = [10, 30]; console.log(typeof(a)); // Object console.log(a.constructor == Array); Console. log(s1 instanceof Stu); </script> </head> <body> <h1>JavaScript language instance -- definition and use of objects </h1> </body> </ HTML >Copy the code
2. JavaScript built-in objects
2.1 Array Array
JavaScript Array object
2.1.1 Creation Method
- var a= new Array(); // Create an empty array
- a = new Array(10); // Create an array of 10 units.
- a=new Array(18, 20, 38); // Create an array of specified array units.
- a=[“a”,”b”,”c”,”d”]; // Quickly define an array
2.1.2 Common Attributes:
- Length: Obtains the length
2.1.3 Common Methods:
- Tostring () : Converts an array to a string and returns the result.
- Sort () : Sorts the elements of an array
- Join () : Puts all the elements of an array into a single string. Elements are separated by the specified delimiter.
- Pop () : Removes and returns the last element of the array
- Push () : Adds one or more elements to the end of the array and returns the new length.
- Shift () : Takes the first element in the array and modifies the length property
- Unshift () : Inserts items at the front of the array, returning the length of the array
- Reverse () : Reverses the array
- Concat () : Concatenates the parameters into the current array
2.1.4 Emptying an Array:
- arr=[]; // Method 1 is recommended
- arr.length = 0; 2 / / way
- arr.splice(0, arr.length); 3 / / way
2.1.5, for example,
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, > <title>Document</title> <script> Var a2 = new Array(10); Var a3 = new Array(10,20,30); // Define an array with a specified value console.log(a1.length); console.log(a2.length); console.log(a3.length); ,20,30,40,50 var a4 = [10]; For (var I =0; i<a4.length; i++){ console.log(i,"=>",a4[i]); } for(var i=a4.length-1; i>=0; i--){ console.log(i,"=>",a4[i]); } for(var i in a4){ console.log(i,"=>",a4[i]); } a4.forEach(function(v){ console.log(v); }); // Array methods: console.log(a4.tostring ()); console.log(a4.join(":")); Var aa = [1, 2, 3]; The console. The log (aa) concat (4, 5)); ,50,30,20,70,40 var b = [10]; console.log(b.join(":")); console.log(b.sort().join(":")); console.log(b.reverse().join(":")); Var aa = new Array(10,20,30); console.log(aa.join(":")); aa.push(50); aa.push(40); console.log(aa.join(":")); aa.pop(); console.log(aa.join(":")); / / to empty the console. The log (b.j oin (" : ")); b.length = 3; console.log(b.join(":")); b = []; console.log(b.join(":")); < / script > < / head > < body > < h1 > JavaScript instance - built-in objects < / h1 > < / body > < / HTML >Copy the code
2.2 Basic Packaging types
Basic packing type
To make it easier to manipulate basic data types, JavaScript also provides three special reference types: String/Number/Boolean
The problem with the following code?
S1 is a primitive type, and primitive types have no methods
var s1 = 'zhangsan' ;
var s2 = s1. substring(5);
Copy the code
When s1.subString (5) is called, s1 is wrapped as a temporary object of type String, subString is called, and the temporary object is destroyed
var s1 = new String( ' zhangsan');
var s2 = s1. substring(5);
s1 = null;
Copy the code
Creates an object of the basic wrapper type
var num =18; Var num = Number('18'); Var num = new Number(18); // Basic wrapper type, objectCopy the code
The Number and Boolean basic wrapper types are rarely used and may cause ambiguity. Such as:
var b1 = new Boolean(false); var b2 = b1 && true; // What is the resultCopy the code
2.3 the Date Date
JavaScript Date object
2.3.1 Common methods
var dd = new Date();
- GetDate () : Returns a day (1-31) in a month from the Date object.
- GetDay () : Returns a day of the week (0 to 6) from the Date object.
- GetMonth () : returns the month (0 to 11) from the Date object.
- GetFullYear () : Returns the year as four digits from the Date object.
- GetYear () : Use the getFullvear() method instead.
- GetHours () : Returns the hour of the Date object (0~23).
- GetMinutes () : Returns the minutes of the Date object (0 to 59).
- Getseconds () : Returns the number of seconds(0 to 59) of the Date object.
- GetMilliseconds () : returns the milliseconds (0 to 999) of the Date object.
- GetTime () : returns the number of milliseconds since January 1, 1970.
As above, there are many other set methods to set.
For example, 2.3.2
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <h1>JavaScript language instance -- built-in object </h1> </body> <script> Function formatDate(dd){if(! dd instanceof Date){ return; } var y = dd.getFullYear(), m = dd.getMonth()+1, d = dd.getDate(), hh = dd.getHours(), mm = dd.getMinutes(), ss = dd.getSeconds(); Hh = hh<10? '0'+hh:hh; mm = mm<10? '0'+mm:mm; ss = ss<10? '0'+ss:ss; return y+"-"+m+"-"+d+" "+hh+":"+mm+":"+ss; } var dd = new Date(); Document. write(" timestamp: "+ dd.valueof ()); document.write("<h2>"+formatDate(dd)+"</h2>"); </script> </html>Copy the code
2.4 String Character String
JavaScript String object
2.4.1 Common methods
- Anchor () : Creates an HTHL anchor.
- *charAt() : Returns the character at the specified position.
- CharCodeAt () : Returns the Unicode encoding of the character at the specified position.
- *index0f() : Retrieves strings.
- *lastIndexOf() : Searches strings from back to front.
- Match () : Finds one or more matches that are being expressed.
- *replace() : Replaces the substring that matches the regular expression.
- Search () : Retrieves the value that matches the regular expression.
- Slice () : A snippet of the promoted string and returns the extracted portion in the new string.
- Split () : Splits a string into an array of strings.
- Substr () : Extracts a specified number of characters from the starting index in the string.
- *substring() : Extracts the character between two specified index numbers in a string.
- TolocaleLowerCase () : Converts the string to lowercase.
- TolocaleUpperCase () : Converts the string to uppercase.
- *toLowerCase() : converts characters toLowerCase.
- *toupperCase() : converts the string toupperCase.
For example, 2.4.2
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <h1>JavaScript language instance -- built-in object </h1> </body> <script> Var s1 = "ZhangSanFeng"; document.write(s1+"<br/>"); document.write(s1[5]+"<br/>"); document.write(s1.charAt(5)+"<br/>"); Document. The write (s1) substr (5, 3) + "< br / >"); Document. The write (s1. The substring (5, 8) + "< br / >"); Document.write (" lowercase: "+ s1.tolowerCase ()+"<br/>"); Document. write(" uppercase: "+ s1.toupperCase ()+"<br/>"); Document.write (s1.indexof ("an")+"<br/>"); document.write(s1.lastIndexOf("an")+"<br/>"); / / replace document. Write (s1) replace (" SanFeng ", "WuJi") + "< br / >"); / / replace all the document. The write (" 10,20,30,40 ". The replace (/, / g, ":") + "< br / >"); var str = "10:23:45:67:87:65"; console.log(str); console.log(str.split(":")); var s2 = " zhangsan "; console.log("#"+s2+"#"); console.log("#"+s2.trim()+"#"); </script> </html>Copy the code
2.5 Math object
JavaScript object of Math
Note: Math objects are not classes of objects like Date and String, so there is no constructor for Math(), and functions like math.sin () are just functions, not methods of an object. You don’t need to create it; you can invoke all of Math’s properties and methods by using it as an object.
2.5.1 Common Methods
- Abs (x) : Returns the absolute value of the number.
- Ceil (x) : The logarithm is rounded up.
- Floor (x) : Logarithms are rounded down.
- Random () : Returns a random number between 0 and 1.
- Round (x) : Round the number to the nearest whole number.
- Max (x,y) : Returns the highest value of x and y.
- Min (x,y) : Returns the lowest value of x and y.
2.5.2 example
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <h1>JavaScript language instance -- built-in object </h1> </body> <script> // built-in object --Math object console.log(Math.abs(-20)); The console. The log (math.h ceil (10.000000001)); // select console.log(math.floor (10.9999999)); // Omit console.log(math.round (10.5)); // round console.log(math.max (10,20)); // round console.log(math.max (10,20)); / / the console. The largest log (Math. Min (10, 20)); // minimum console.log(math.random ()) //0~1 random number console.log(math.ceil (math.random ()*1000000)%10+1) </html>Copy the code
2.6 Global
- Escape (string) : The string can be encoded
- Unescape (string) : The function decodes the string encoded by escape().
- EncodeURI (URIstring) : Function can encode a string as a URI.
- DecodeURI (URIstring) : function to decode urIs encoded by encodeURI().
- Peval (string) : The function evaluates a string and executes the JavaScript code inside it.
- GetClass (Javaobj) : The function returns a JavaClass of a Javaobject
- *isNaN(x) : The function checks whether its arguments are non-numeric values.
- Number(object) : The function converts the value of an object to a Number.
- *parsef loat(string) : Returns parses a string and returns a floating point number.
- *parseInt(string, radix)
3. JavaScript clicks on the event and element tags
JavaScript event
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> <h1 id="hid">JavaScript language instance -- click the event </h1> <button Onclick = "fun ()" > click me < / button > < ul id = "uid" > < li > AAAAA < / li > < li > BBBBB < / li > < li > CCCCC < / li > < li > DDDDD < / li > < / ul > < ol > <li>1111111</li> <li>2222222</li> </ol> </body> <script> function fun(){ console.log('hello js'); Var hid = document.getelementById ("hid"); // Output the text content between element tags console.log(hid.innerhtml); Hid. InnerHTML = "JavaScript language instance -- element operation "; // Change the style of the HTML element hid. Style. color = "red"; // hid.style.background-color = "#ddd"; Because the naming conflicts When this code is error Can be changed to the following code hid. Style. BackgroundColor = "# DDD"; / / remove - and will - after the lowercase letters to uppercase} / / access to all the li elements in the label for the current page / / var mlist = document. The getElementsByTagName (" li "); var mlist = document.getElementById("uid").getElementsByTagName("li"); For (var I in mlist){if(! isNaN(i)){ console.log(mlist[i].innerHTML); mlist[i].style.color="red"; } } </script> </html>Copy the code
4. Timing events in JavaScript
JavaScript event Timing
4.1 Timing events
4.2 How Do I Stop the vm?
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>Document</title> </head> <body> </button onclick="doStop()"> </button> </body> <script> var m=0,mytime=null; function doRun(){ m++; Document.getelementbyid ("hid").innerhtml = "counter: "+m; mytime = setTimeout(doRun,1000); } doRun(); function doStop(){ clearTimeout(mytime); } /* m = 0; var mytime = setInterval(function(){ m++; Document.getelementbyid ("hid").innerhtml = "counter: "+m; },1000) function doStop(){ clearInterval(mytime); } setTimeout(function(){console.log("Hello JS!"){console.log("Hello JS! ); }, 3000); Var m = 0; setInterval(function(){ m++; console.log("Hello "+m); },1000) */ </script> </html>Copy the code
5, JavaScript implementation of a simple calculator instance
Simple data acquisition, calculation and display through javascript
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, </h1> <form action="" name="myform" Method ="get"> num1: <input type="text" name="num1" size="10"/><br/><br/> <input type="text" name="num2" size="10"/><br/><br/> 结 果 : <br/><br/> <br/> Size ="10"/><br/><br/> <br/>< input type="button" onclick="doFun(1)" value=" />< input type="button" onclick="doFun(2)" Value =" minus "/> <input type="button" onclick="doFun(3)" value=" x "/> <input type="button" onclick="doFun(4)" value=" x "/> < / form > < / body > < script > / / handler function doFun (c) {var m1 = parseInt (value). The document myform. Num1.; var m2 = parseInt(document.myform.num2.value); //console.log(m1,m2); switch(c){ case 1: var res = m1+"+"+m2+"="+(m1+m2); break; case 2: var res = m1+"-"+m2+"="+(m1-m2); break; case 3: var res = m1+"*"+m2+"="+(m1*m2); break; case 4: var res = m1+"/"+m2+"="+(m1/m2); break; } / / place the results to the third document in the input box. The myform. Res., value = res; } </script> </html>Copy the code
6. JavaScript simply manipulates element tag instances
Control HTML element size through JavaScript
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial scale=1.0"> <title>Document</title> </head> <body> <h1 </button onclick="dofun(1)"> zoom </button> </button onclick="dofun(2)"> zoom </button> </button onclick="dofun(3)"> hide </button> <br/><br/> <div style="width:200px; height:200px; background-color:#ddd;" id="did"></div> </body> <script> var width=200,height=200; var did = document.getElementById("did"); Function dofun(m){switch(m){case 1: width += 10; height += 10; did.style.width = width+"px"; did.style.height = height+"px"; break; case 2: width -= 10; height -= 10; did.style.width = width+"px"; did.style.height = height+"px"; break; case 3: did.style.display = "none"; break; } } </script> </html>Copy the code
7. JS event processing
Reference: HTML DOM Event objects
7.1 Event Binding Mode
Event source, event, event handler
There are two event binding methods:
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>JavaScript language instance </title> </head> <body> <h1>JavaScript language instance -- event handling (event binding)</h1> <button Onclick ="fun()"> 1</button> </button id="bid"> 2</button> </body> </ script> Console. log(" button 1 was clicked "); } // document.getelementById ("bid").onclick = function(){console.log(" button 2 was clicked "); } </script> </html>Copy the code
7.2 Obtaining event Source Objects
The two event binding methods correspond to two methods of obtaining event source objects
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial-scale =1.0"> <title>JavaScript language instance </title> </head> <body> <h1>JavaScript language instance -- get the event source object </h1> <h2 Onclick ="fun(this)"> 1</h2> <h2 id="hid">2 </h2> </body> <script> / function fun(){// console.log("aaaaaaaaaa"); // // in this event binding mode, this indicates the outer object, cannot get the current event source object // console.log(this); Function fun(ob){console.log("aaaaaaaaaa"); console.log(ob); ob.style.color = "green"; } // document.getelementById ("hid").onclick = function(){console.log(" BBBBBBBBBBB "); //console.log(this); //console.log(this); this.style.color = "red"; } </script> </html>Copy the code
7.3 Bclick Double-click event
<! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Word-wrap: break-word! Important; "> < span style> ul,li{margin:0px; padding:0px; } ul{list-style:none; } ul li{height:30px; margin-top:4px; background-color:#ddd; } ul li:hover{background-color:#fc0; } < / style > < / head > < body > < h1 > JavaScript instance, dblclick double-click events < / h1 > < ul > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < li > < / li > < / ul > < / body > < script > / / get all the above var mlist = li element node document.getElementsByTagName("li"); For (var I =0; i<mlist.length; I++) {mlist [I] ondblclick = function () {/ / set the background color. This style. The backgroundColor = "# f0c"; } } </script> </html>Copy the code
The chapters are summarized here (the better we understand you guys ~ 3 ~), the better we understand you guys.
Have a question welcome to ask, everyone together in learning Java on the road to play strange upgrade! (O ゜ – ゜▽゜)