JavaScript Language Essentials click to download, password: synu

1. The birth of JavaScript language is mainly to complete the data verification of the page. 2. It runs on the client side and requires a browser to parse and execute JavaScript code. 3.JS is a product of Netscape, originally named LiveScript. To attract more Java programmers. Change the name to javascript. JS is weakly typed and Java is strongly typed.

JavaScript features: 1. Interactivity (all it can do is dynamically exchange information) 2. Security (do not allow direct access to the local hard disk) 3. Cross-platform (as long as the browser can interpret Js can be executed, platform independent)

The first way to combine JavaScript and HTML code is just to write JavaScript code in the head tag, or in the body tag, using the Script tag

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <! <script type="text/javascript"> It just pops up something alert("js hello"); </script> </head> <body> </body> </html>Copy the code

The second approach uses the Script tag to introduce a separate JavaScript code file

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <! The script tag can be used to define JS code, and can also be used to import individual JS file SRC properties to set the path (relative or absolute) of the js file to be imported. A script tag can only do one thing. Either to define js code, <script type="text/javascript" SRC ="1.js"></script> <script type="text/javascript"> alert(2222); </script> </head> <body> </body> </html>Copy the code

Variables What is a variable? Variables are the names of memory that can hold certain values.

JavaScript variable type: number int Short Long float Double byte String type: string Object type: Object Boolean type: Boolean Function type: function

The default values are undefiend null and NAN not a number (NAN is not a number).

Var variable name; Var Variable name = value;

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> var i ; // alert(i); // undefiend i = 12 ; // typeof is a function. // alert(typeof(I)); // number i = "this is good boy!" ; alert( typeof(i) ); //string </script> </head> <body> </body> </html>Copy the code

Relational (comparison) operations

Equal to: == All: === =

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> var a = 12; var b = "12"; // alert(a == b); alert(a == b); Alert (a === b); alert(a == b); //false </script> </head> <body> </body> </html>Copy the code

Logic operations and operations: && or operation: | | invert operation:! 0, null, undefined, “” (empty string) are considered false;

&& and operations. There are two cases: the first is when all expressions are true. Returns the value of the last expression. Second: when one of the expressions is false. Returns the value of the expression whose first is false

| | or operation The first kind of circumstance: when expression all is false, returns the value of the last expression The second case: as long as there is an expression is true. Will get back to the first value for true expression and && with operation and | | or a faulty operation. Short circuit that is to say, when the && and | | operation have the results later. The following expression is no longer executed

<head> <meta http-equiv="Content-Type" content="text/html; Charset = utF-8 "> <title>Insert title here</title> <script type="text/javascript"> // 0, null, undefined, "(empty string False; // var a = 0; // if (a) {// alert(" zero is true "); //} else {// alert(" zero is false "); // } // var b = null; // if (b) {// alert("null is true "); //} else {// alert("null false "); // } // var c = undefined; // if (c) {// alert("undefined "); //} else {// alert("undefined "); // } // var d = ""; // if (d) {// alert(" null string true "); //} else {// alert(" empty string false "); // } var a = "abc"; var b = true; var d = false; var c = null; // && and operations. // There are two cases: // The first case is when all expressions are true. Returns the value of the last expression. // alert( b && a ); //abc // alert( a && b ); //true // second: when one of the expressions is false. Return the value of the first false expression // alert(d &&c); // false // alert( a && c ); / / null / / | | or operation / / the first kind of circumstance: when expression all is false, returns the value of the last expression / / alert (d | | c); // null // alert( c || d ); // false // Second case: only one expression is true. Will get back to the first is true the value of the expression / / alert (b | | c); // true // alert( d || a ); // abc </script> </head>Copy the code

Var array name = []; Var Array name = [value 1, value 2, value 3]; // Define an array and assign an initial value

<head> <meta http-equiv="Content-Type" content="text/html; Charset = utF-8 "> <title>Insert title here</title> <script type="text/javascript"> // Define an empty array var arr = []; // alert( arr.length ); //0 arr[0] = 12; // alert(arr[0]); //12 // alert( arr.length ); //1 // js arrays are automatically expanded according to the maximum subscript when assigned by download. arr[2] = "abc"; // alert( arr.length ); //3 // alert( arr[1] ); // for (var I = 0; i < arr.length; i++) { // alert( arr[i] ); Var array name = [value 1, value 2, value 3]; Var arr2 = [12," ABC ",true]; // alert(arr2.length); // 3 arr2[9] = 12; alert(arr2.length); </script> </head>Copy the code

Function: Two ways to define a function The first way to define a function is using the function keyword. The format is as follows:

Function Name (parameter list) {function body}

How to access a function: function name (argument list);

How do I define a function with a return value? A: Just use the return statement directly inside the function to return the value.

<script type="text/javascript"> // function fun(){// alert(" this function is called without arguments "); // function fun(){// alert(" this function is called without arguments "); / /} / / / / a parameter function function fun2 (a, b) {/ / alert (" there is reference function is called a = > "+ a +", "b" = > "+ b); Function sum(num1, num2){return num1 + num2; } // How to access the function: function name (argument list); // alert( sum("abc",100) ); </script>Copy the code

The second way to define a function is: var function name = function(argument list){function body}

<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> var fun = function(num){ Alert (" second definition of function: "+ num); } fun(123); </script> </head>Copy the code

Note: Functions are allowed to overload in Java. In Js, however, function overloading overwrites the previous definition

<script type="text/javascript"> function fun(a,b){ alert(a); alert(b); Alert (" parameter function called "); } function fun(){alert(" function called without arguments "); } fun(12,"abc",true); </script>Copy the code

Public void fun(int a, Object… The args)… Args is a variable length parameter which is itself an array. Js functions come with an invisible argument that basically uses the same arguments as Java variable length arguments. Are used to receive any number of parameters. It is used just like an array.

<script type="text/javascript"> function fun(a,b){ alert(a); alert(b); Alert (" parameter function called "); } function fun(pa,pb){ alert( arguments.length ); //3 alert( arguments[0] ); //12 alert( arguments[1] ); //abc alert( arguments[2] ); //true alert("====================="); alert( pa ); //12 alert( pb ); // ABC alert(" no argument function called "); } // fun(12,"abc",true); Function sum(){var result = 0; function sum(){var result = 0; for (var i = 0; i < arguments.length; i++) { if ( typeof(arguments[i]) == "number" ) { result += arguments[i]; } } return result; } alert (sum (100, "ABC", 100100)); </script>Copy the code

Var var = new Object(); Creates an object instance (empty) variable name. Attribute name = value; Defines an attribute variable name for an object instance. Function name = function(){} To the object instance, add a method how to access the object: variable name. Property name/method name ()

<script type="text/javascript"> var obj = new Object(); Obj. Name = "I'm so handsome!" ; obj.age = 18; Obj. fun = function(){alert(" name: "+ this.name + ", age:" + this.age); } // access object // alert(obj.name); obj.fun(); </script>Copy the code

Var var = {// define an empty object property name: value, // define a property function name: function(){} // define a function}; How to access objects: variable names. Property name/method name ()

<script type="text/javascript"> var obj = {name:" hoy ", age:18, fun:function(){alert(" name:" + this.name + ", age:18) " + this.age); }}; alert(obj.name); obj.fun(); </script>Copy the code

Events in JS (important) What is an event? An event is a response from a computer input device that interacts with a page. We call them events.

The onLoad completion event is used to automatically initialize the page after it has been loaded by the browser. Onblur Out-of-focus events are used when an input box loses focus. Verify that the content is valid onChange Events are used to respond to changes in the input field or drop-down list. Onsubmit form submission events are used to verify that all form entries are valid before submission. As long as one of them is illegal, block form submission.

Event registration is divided into static registration and dynamic registration of two kinds: registration event and binding event is a thing registration event, is to tell the browser, when the event triggered, need to execute the code.

Static registration of events: Static registration refers to code that is directly assigned to the event response via the event attribute. This method is called static registration.

Dynamic registration event: Dynamic registration is achieved by first retrieving the label object. And then through the label object. Function (){}. This operation is called dynamic registration.

Window.onload = function(){1 find the tag object 2 pass the tag object. Function (){}} onload

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.onload = function(){ Alert (" page load complete == dynamic "); } </script> </head> <! Static register <body "alert(' page loaded! ');" > --> <body> </body> </html>Copy the code

Sample code for the onclick event:

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function onclickFun(){ Alert (" This is a click event static registration "); Function (){// getElementById = getElementById; // getElementById = getElementById; // GetElement = Element; // By by.. Var btnObj = document.getelementById ("btn01"); var btnObj = document.getelementById ("btn01"); // alert( btnObj ); // 2 Pass the label object. Function (){} btnobj.onclick = function(){alert(" this is a dynamic onclick event "); } } </script> </head> <body> <! <input type="button" value=" 1" onclick="onclickFun(); / > 2 < button id = "btn01" > button < / button > < / body > < / HTML >Copy the code

Onblur Out-of-focus events

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function onblurFun(){ // Console is an object provided in JS specifically for debugging. The console // log method is output. You can pass any parameter console.log(" This is the static registration of the onblur event "); } window.onload = function(){var passObj = document.getelementById ("password"); //2 Pass the label object. Function (){} passobj.onblur = function(){console.log(" this is a dynamic registration of onblur events "); </script> </head> <body> user name: <input type="text" onblur="onblurFun();" / > < br / > password: < input id = "password" type = "password" / > < br / > < / body > < / HTML >Copy the code

Onchange Event that the content changes

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function onchangeFun(){ Alert (" static register onchange event "); } window.onload = function(){var selObj = document.getelementById ("sel01"); // alert( selObj ); //2 Pass the label object. Function (){} selobj. onchange = function(){alert(" onchange "); <select onchange="onchangeFun(); </option> <option> <option> <option> <option> <option> <select id="sel01"> <option>-- select --</option> <option> <option> <option> John </option> </select> </body> </ HTML >Copy the code

Onsubmit Form submission event

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset = utF-8 "> <title>Insert title here</title> <script type="text/javascript"> function onsubmitFun(){alert(" Found illegal "); return false; } // window.onload = function(){var formObj = document.getelementById ("form01"); // alert(formObj); // Pass the label object. Function (){} formObj. Onsubmit =function(){alert(); return false; } } </script> </head> <body> <! -- OnSubmit event, return false. <form action="http://www.baidu.com" onsubmit="return onsubmitFun();" <form > <form action="http://www.baidu.com" id="form01"> <form type="submit" Value =" dynamic register "/> </form> </body> </ HTML >Copy the code

DOM is a Document Object Model that converts labels, attributes, and text in documents into objects for management. First point: The Document object manages all the Html Document content. Second point: document is a tree structured document. There is hierarchy. Number three: it allows us to objectify all tags. Number four: We can access all tag objects through document.

What is objectification? Our basic class has studied object orientation. What is objectification? For example: there is a person has age: 18 years old, gender: female, name: Zhang so-and-so we want to put this person’s information objectification how to do!

Class Person {
private int age;
private String sex;
private String name;
}
Copy the code

What about HTML tags that need to be objectified?

  <body>
	<div id="div01">div01</div>
  </body>
Copy the code

Analog object, equivalent to: class Dom{private String ID; // Id attribute private String tagName; Private Dom parentNode; Private List children; // Child node private String innerHTML; / / in the middle of the start tag and the end tag content} Document object method is introduced in (* * * * * key) 1. The Document. The getElementById (elementId) via the tag’s id attribute tags dom object, elementId is the id attribute value of the label

2. Document. GetElementsByName (elementName) through the tag’s name attribute to find dom object, elementName tag’s name attribute value

3. Document. GetElementsByTagName (tagname) label dom object via the tag name. Tagname is the label name

The document.createelement (tagName) method creates a tag object with the given tagName. TagName is the name of the tag to be created

If the tag object has an ID attribute, use getElementById to find the tag object preferentially. If the tag has no ID attribute, only name attribute, use getElementsByName to find the tag object. If the tag has neither ID nor name attribute, GetElementsByTagName and getElementById and getElementsByName and getElementsByTagName need to be executed after the page is loaded. To get the label object.

Example code for the getElementById method:

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset = utf-8 "> <title>Insert title here</title> <script type="text/javascript"> Function onclickFun(){function onclickFun(){function onclickFun(){function onclickFun(){function onclickFun(){function onclickFun(){function onclickFun(){ Make sure you get the tag object first. var usernameObj = document.getElementById("username"); var usernameText = usernameObj.value; Var spanObj = document.getelementById ("usernameSpan"); InnerHTML = "spanobj. innerHTML "; // This attribute is readable and writable. Var patt = /^\w{5,12}$/; The rules for validation are: it must consist of letters, numbers, underscores, and be 5 to 12 characters long. If (patt.test(usernameText)) {// spanobj.innerhtml = "User name valid "; spanObj.innerHTML = "<img alt=\"\" src='right.png' width='15' height='15' />"; } else {// spanobj. innerHTML = "The user name is invalid "; spanObj.innerHTML = "<img alt=\"\" src='wrong.png' width='15' height='15' />"; </script> </head> <body> <input type="text" id="username" value="wzg168"/> <span style="color: red; Id ="usernameSpan"></span> <button onclick="onclickFun()">Copy the code

Example code for the getElementsByName method:

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset = utF-8 "> <title>Insert title here</title> <script type="text/javascript" When we want to manipulate a label object. Make sure you get the tag object first. //getElementsByName is a collection of objects returned based on the name attribute. / as / / / this collection operation with an array of elements in the collection order is that they are just in the HTML page, from top to bottom in the order of var hobbies = document. The getElementsByName (" hobby "); // Checked indicates the checked status of the checkbox. For (var I = 0; i < hobbies.length; i++) { hobbies[i].checked = true; }} / / all don't choose the function checkNo () {var hobbies = document. The getElementsByName (" hobby "); // Checked indicates the checked status of the checkbox. For (var I = 0; i < hobbies.length; i++) { hobbies[i].checked = false; }} / / the selected function checkReverse () {var hobbies = document. The getElementsByName (" hobby "); // Checked indicates the checked status of the checkbox. For (var I = 0; i < hobbies.length; i++) { // if (hobbies[i].checked) { // hobbies[i].checked = false; // } else { // hobbies[i].checked = true; // } hobbies[i].checked = ! hobbies[i].checked; </script> </head> <body> <input type="checkbox" name="hobby" checked="checked" value=" hJ "/> Drinking <input type="checkbox" name="hobby" value="cy"/> smoking <input type="checkbox" name="hobby" value="tt"/> <button onclick="checkAll(); <button onclick="checkNo();" <button onclick="checkReverse();" </button> </body> </ HTML >Copy the code

Example code for the getElementsByTagName method:

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset = utF-8 "> <title>Insert title here</title> <script type="text/javascript"> //getElementsByTagName is a collection of tag objects that are retrieved by the specified tag name. // The order of the elements in this collection is the same as they are in the HTML page, from top to bottom! var inputObjs = document.getElementsByTagName("input"); for (var i = 0; i < inputObjs.length; i++) { inputObjs[i].checked = true; </script> </head> <body> <input type="checkbox" checked="checked" value=" hJ "/> Drinking <input type="checkbox" value="cy"/> smoking <input type="checkbox" Value = "tt" / > broth < br / > < button onclick = "checkAll ();" </button> </body> </ HTML >Copy the code

Example code for the createElement method:

<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset = utF-8 "> <title>Insert title here</title> <script type="text/javascript"> window.onload = function(){ Create tag with code: <div> Handsome guy awesome! </div> and add it to the body tag to show var divObj = document.createElement("div"); //<div></div> // alert( divObj ); // divobj. innerHTML = "I'm so cute!" ; //<div> </div> var textNode = document.createTextNode ); divObj.appendChild( textNode ); / / the appendChild add child element to the body tag document. The body. The appendChild (divObj); } </script> </head> <body> </body> </html>Copy the code

The common attributes and methods of nodes, called nodes, are the label objects mentioned above.

Method: Call getElementsByTagName() on the element node to get the specified tag name of the current node. Child node appendChild(oChildNode) is the child node to be added

Properties: Get firstChild of the current node, lastChild of the current node, parentNode, nextSibling of the current node, Get the previousSibling attribute of the next node of the current node, get the className attribute of the previous node of the current node, and get or set the innerHTML attribute of the tag’s class attribute. The innerText property gets or sets the text in the start and end tags

Exercise: 05.DOM query exercise

<! DOCTYPE HTML > < HTML > <head> <meta charset="UTF-8"> <title> DOM query </title> <link rel="style "type="text/ CSS" href="style/css.css" /> <script type="text/javascript"> window.onload = function(){ //1. Document.getelementbyid ("btn01").onclick = function(){alert(document.getelementById ("bj").innerhtml); Var btn02Ele = document.getelementById ("btn02"); btn02Ele.onclick = function(){ alert( document.getElementsByTagName("li").length ); }; Var btn03Ele = document.getelementById ("btn03"); btn03Ele.onclick = function(){ alert( document.getElementsByName("gender").length ); }; Var btn04Ele = document.getelementbyId ("btn04"); var btn04Ele = document.getelementbyId ("btn04"); Btn04el. onclick = function(){//1 = function(){//1 = function(); document.getElementById("city").getElementsByTagName("li").length ); }; Var btn05Ele = document.getelementById ("btn05"); var btn05Ele = document.getelementById ("btn05"); Btn05ele.onclick = function(){document.getelementById ("city").childnodes.length); //2 passes the city object. Get all child nodes}; Var btn06Ele = document.getelementById ("btn06"); Btn06ele.onclick = function(){document.getelementById ("phone").firstChild.innerhtml; //2 Query the first child node}; Var btn07Ele = document.getelementById ("btn07"); var btn07Ele = document.getelementById ("btn07"); Btn07ele.onclick = function(){document.getelementById ("bj").parentNode.innerhtml); }}}}; Var btn08Ele = document.getelementById ("btn08"); btn08Ele.onclick = function(){ alert( document.getElementById("android").previousSibling.innerHTML ); }; Var btn09Ele = document.getelementbyId ("btn09"); btn09Ele.onclick = function(){ alert( document.getElementById("username").value ); }; Var btn10Ele = document.getelementById ("btn10"); Btn10el.onclick = function(){document.getelementById ("username"). }; Var btn11Ele = document.getelementById ("btn11"); btn11Ele.onclick = function(){ // alert( document.getElementById("bj").innerText ); alert( document.getElementById("city").innerText ); }; }; </script> </head> <body> <div id="total"> <div class="inner"> <p> Which city do you like? < / p > < ul id = "city" > < li id = "bj" > Beijing < / li > < li > Shanghai < / li > < li > Tokyo < / li > < li > Seoul < / li > < / ul > < br > < br > < p > stand-alone game do you like? < / p > < ul id = "game" > < li id = "rl" > alert < / li > < li > live < / li > < li > gourmet coaster < / li > < li >, < / li > < / ul > < br / > < br / > < p > your phone's operating system? </p> <ul id="phone"><li>IOS</li><li id="android">Android</li><li>Windows Phone</li></ul> </div> <div class="inner"> gender: <input type="radio" name="gender" value="male"/> Male <input type="radio" name="gender" value="female"/> Female <br> <br> name: <input type="text" name="name" id="username" value="abcde"/> </div> </div> <div id="btnList"> <div><button Id ="btn01"> </button></div> <div><button id="btn02"> </button></div> <div><button Id ="btn03"> </button></div> <div><button id="btn04"> </button></div> <div><button id="btn04" Id =" bTN05 "> returns all child nodes of #city </button></div> <div><button ID =" bTN06 "> returns the first child node of #phone </button></div> <div><button Id ="btn07"> returns the parent of #bj </button></div> <div><button ID =" bTN08 "> returns the previous sibling of # Android </button></div> <div><button Id ="btn09"> return #username value </button></div> <div><button id="btn10"> Set #username value </button></div> <div Id = "btn11" > returns the text value of # bj < / button > < / div > < / div > < / body > < / HTML >Copy the code