catalogue
2. Basic syntax of JavaScript (ECMAScript)
2.5.1 common events and event registration methods
2.5.4 capture keyboard press events
3.2 get the value of the text box
3.3 innerHTML and innerText attributes to operate div and span
3.4 remove the blank trim before and after the string
3.6 select all and deselect all check boxes
3.7 get the value of the selected item in the drop-down list
3.9 internal support class Array
2. Basic syntax of JavaScript (ECMAScript)
2.5 events
2.5.1 common events and event registration methods
Common events in JS:
1.blur: loss of focus
2.focus: gain focus
3.click: mouse click
4.dblclick: double click the mouse
5.keydown: press the keyboard
6.keyup: the keyboard pops up
7.mousedown: mouse down
8.mouseover: mouse over
9.mousemove: mouse movement
10.mouseout: mouse out
11.mouseup: the mouse pops up
12.reset: form reset
13.submit: form submission
14.change: the selected item in the drop-down list changes, or the content of the text box changes
15.load: the page is loaded
16.select: text for selection
Any event will correspond to an event handle. The event handle is to add on before the event. onXXX this event handle appears in the attribute position of a label, and the event handle exists in the form of an attribute.
The event will trigger the callback function. The callback function is characterized by writing the function code by itself, but this function is not called by itself, and other programs are responsible for calling this function.
There are two ways to register events:
① Use event handles directly in Tags
② Complete the event registration using pure JS code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS Common events for</title> </head> <body> <script type="text/javascript"> //For the current program, the sayHello function is called a callback function (callback function) //Characteristics of callback function: I wrote the function code myself, but this function is not called by myself, and other programs are responsible for calling this function. function sayHello() { alert("hello js!"); } </script> <!--The first way to register time is to use the event handle directly in the tag--> <!--The meaning of the following code is: sayHello Register the function on the button and wait click After the event occurs, the function is called by the browser. We call this function a callback function.--> <input type="button" value="hello" onclick="sayHello()"/> <input type="button" value="hello2" id="mybtn"/> <input type="button" value="hello3" id="mybtn1"/> <input type="button" value="hello4" id="mybtn2"/> <script type="text/javascript"> function doSome() { alert("do some!"); } /* The second way to register events is to use pure JS code to complete event registration. */ //Step 1: get the button object first (document is all lowercase, built-in object, which can be used directly, and document represents the whole HTML page) var btnObj = document.getElementById("mybtn");//Get this element by id //Step 2: assign a value to the onclick attribute of the button object btnObj.onclick = doSome;//Note: do not add parentheses. btnObj.onclick = doSome(); This is the wrong way to write. var mybtn1 = document.getElementById("mybtn1"); mybtn1.onclick = function () {//This function has no name and is called an anonymous function. This anonymous function is also a callback function. //This function is only registered when the page is opened and will not be called until the click event occurs. alert("test..."); } document.getElementById("mybtn2").onclick = function () { alert("test2...."); } </script> </body> </html>
2.5.2 code execution sequence
Add a page loading completion event load.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS Execution order of code</title> </head> <body> <script type="text/javascript"> /* window.onload = ready;//The ready function will not be executed until all pages are loaded. function ready() { var btn = document.getElementById("btn"); btn.onclick = function () { alert("hello js"); } } */ //During page loading, the a function is registered with the load event //After the page is loaded, the load event occurs, and the callback function a is executed //During the execution of callback function a, function b is registered with the click event with id = "btn" //When the click event occurs on the node with id="btn", the b function is called and executed. window.onload = function () {//This callback function is called a document.getElementById("btn").onclick = function () {//This callback function is called b alert("hello js"); } } </script> <input type="button" value="hello" id="btn"/> </body> </html>
2.5.3 setting node properties
After obtaining the element through id, you can use "." to access the attribute of the element and modify the attribute value.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS Code sets the properties of the node</title> </head> <body> <script type="text/javascript"> window.onload = function () { document.getElementById("btn").onclick = function () { var mytext = document.getElementById("mytext"); //Any attribute in a node object can be "." mytext.type = "checkbox"; } } </script> <input type="text" id="mytext"/> <input type="button" value="Change the text box to a check box" id="btn"/> </body> </html>
2.5.4 capture keyboard press events
Capture the Enter key.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS Code capture enter key</title> </head> <body> <script type="text/javascript"> window.onload = function () { var uesenameElt = document.getElementById("username"); //The key value of the Enter key is 13 and the key value of the ESC key is 27 /* uesenameElt.onkeydown = function (a,b) { alert(a);//[object KeyboardEvent] When this event occurs, the browser will create a new object and pass it back alert(b);//undefined } */ /* uesenameElt.onkeydown = function (event) { //Get key value //For the "keyboard event object", there is a keyCode attribute to obtain the key value. alert(event.keyCode); } */ uesenameElt.onkeydown = function (event) { if(event.keyCode === 13){ alert("Validation in progress"); } } } </script> <input type="text" id="username"/> </body> </html>
2.6 void operator
Syntax format: void (expression)
Operation principle: execute the expression without returning any results
For example, the following example: if void does not return any results, there will be no jump path for href, and the page will not jump.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS of void operator</title> </head> <body> Top of page<br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br> <!-- void Syntax of operator: void(expression) Operation principle: execute the expression without returning any results. javascript:void(0) among javascript:The function is to tell the browser that there is a paragraph after it JS code. Of the following procedures javascript:It cannot be omitted. --> <a href="javascript:void(0)" onclick="window.alert('test code')"> The style of the hyperlink is retained, and a paragraph is executed when the user clicks the hyperlink JS Code, but the page can't jump. </a> <a href="javascript:void(100)" onclick="window.alert('test code')"> The style of the hyperlink is retained, and a paragraph is executed when the user clicks the hyperlink JS Code, but the page can't jump. </a> <!--void()Parentheses cannot be left blank. There must be an expression within this parenthesis. <a href="javascript:void()" onclick="window.alert('test code')"> The style of the hyperlink is retained, and a paragraph is executed when the user clicks the hyperlink JS Code, but the page can't jump. </a> --> <br><br><br><br><br><br><br><br><br><br><br><br> </body> </html>
2.7 control statement
①if
②switch
③while
④do...while...
⑤ for loop
⑥break
⑦continue
⑧ for...in statement
⑨ with statement
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS Control statement for</title> </head> <body> <script type="text/javascript"> //Create JS array var arr = [false,true,1,2,"abc",3.14];//The types of elements in JS array are arbitrary. The number of elements is arbitrary //Traversal array for(var i = 0;i < arr.length;i++){ alert(arr[i]); } //for..in.. for(var i in arr){ alert(i);//i is the subscript of the array alert(arr[i]); } //The for..in.. statement can traverse the properties of an object User = function (username,password) { this.username = username; this.password = password; } var u = new User("zhangsan","111"); alert(u.username + "," + u.password); alert(u["username"] + "," + u["password"]); for(var shuXingMing in u){ //alert(shuXingMing); //alert(typeof shuXingMing);//shuXingMing is a string alert(u[shuXingMing]);//shuXingMing itself is a string. There is no need to add double quotes here. } alert(u.username); alert(u.password); with(u){ alert(username + "," + password); } </script> </body> </html>
3.DOM programming
3.1 DOM overview
JS includes three parts: ECMAScript, DOM and BOM.
① ECMAScript: the core syntax of JS (ES specification / ECMA-262 standard)
②DOM: Document Object Model. Document object model: the process of adding, deleting and modifying nodes in web pages.
HTML documents are treated as a DOM tree.
③BOM: Browser Object Model. Browser object model: close the browser window and open a new browser
Window, back, forward, address on browser, etc.
Differences and relations between DOM and BOM:
The top-level object of BOM is window
The top-level object of DOM is document
In fact, BOM includes DOM.
3.2 get the value of the text box
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DOM programming-Gets the name of the text box value</title> </head> <body> <script type="text/javascript"> window.onload = function () { var btnElt = document.getElementById("btn"); btnElt.onclick = function () { /* //Get username node var usernameElt = document.getElementById("username"); var username = usernameElt.value; alert(username); */ //Get text box content //alert(document.getElementById("username").value); //You can modify his value document.getElementById("username").value = "zhangsan"; } } </script> <!--<input type="button" id="btn" value="hello"/>--> //Assign the contents of text box 1 to text box 2 <input type="text" id="username"/> <input type="button" value="Gets the name of the text box value" id="btn"/> <hr> <script type="text/javascript"> window.onload = function () { var btnElt1 = document.getElementById("btn1"); btnElt1.onclick = function () { document.getElementById("username2").value = document.getElementById("username1").value; } } </script> <input type="text" id="username1"/> <br> <input type="text" id="username2"/> <br> <input type="button" value="Assign the contents of text box 1 to text box 2" id="btn1"> <br> <!--blur Event: loss of focus event--> <!--In the following code this Represents the current input Node object.this.value This is the node object value Properties.--> <input type="text" onblur="alert(this.value)"/> </body> </html>
3.3 innerHTML and innerText attributes to operate div and span
Difference between innerHTML and innerText attributes:
The same point: they all set the content inside the element.
difference:
① innerHTML will interpret and execute the following string as an HTML code;
② Even if innerText is followed by a piece of HTML code, it is just treated as an ordinary string.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>innerHTML and innerText operation div and span.html</title> <style type="text/css"> #div1{ background-color: aquamarine; width: 300px; height: 300px; border: 1px red solid; position: absolute; left: 100px; top: 100px; } </style> </head> <body> <script type="text/javascript"> window.onload = function () { var btn = document.getElementById("btn"); btn.onclick = function () { //Set div content //Step 1: get div object var divElt = document.getElementById("div1"); //Part 2: use the innerHTML attribute to set the elements inside the element //divElt.innerHTML = "xxy Lala Lala"; divElt.innerHTML = "<font color='red'>User name cannot be empty!</font>"; //Divelt. InnerText = "< font color ='Red '> user name cannot be empty! < / font >"; } } </script> <input type="button" value="set up div Content in" id="btn"/> <div id="div1"></div> </body> </html>
3.4 remove the blank trim before and after the string
Note: the lower version of IE browser does not support String trim() function. At this time, you can extend a new trin() function to the String class.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Remove whitespace before and after string trim</title> </head> <body> <script type="text/javascript"> //The lower version of IE browser does not support string trim() function. What should I do? //You can extend a new trim() function to the String class yourself /* String.prototype.trim = function () { //alert("Extended trim method ""); //Removes the front and back whitespace of the current string //this in the current method represents the current string //return this.replace(/^\s+/,"").replace(/\s+$/,"");//Regular expression is used to remove the front and back blank lattice return this.replace(/^\s+|\s+$/g,""); } */ window.onload = function () { document.getElementById("btn").onclick = function () { //Get user name var username = document.getElementById("username").value; //Remove front and back blanks username = username.trim(); //test alert("---->" + username + "<----"); } } </script> <input type="text" id="username"/> <input type="button" value="Get user name" id="btn"/> </body> </html>
3.5 realize form verification
Implement a simple form verification function.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form Validation </title> <style type="text/css"> span{ color: red; font-size: 12px; } </style> </head> <body> <script type="text/javascript"> /* (1)User name cannot be empty (2)The user name must be between 6 and 14 digits (3)The user name can only consist of numbers and letters, and cannot have other symbols (regular expressions) (4)The password is consistent with the confirmation password, and the email address is legal (5)Unified lost focus verification (6)The error prompt information shall be uniformly prompted in the span label, and it shall be in 12 point font and red. (7)After the text box gets the focus again, clear the error message prompt. If the data in the text box is illegal, it is required to clear the value of the text box (8)All items in the final form can be submitted only if they are legal. */ window.onload = function () { var usernameElt = document.getElementById("username"); //Get the span tag of username var usernameErrorSpan = document.getElementById("usernameError"); //Bind blur event to user name text box usernameElt.onblur = function () { //Get user name var username = usernameElt.value; //Remove front and back blanks username = username.trim(); //Judge whether the user name is empty if(username){ //Represents that username is not an empty string if(username.length <= 14 && username.length >= 6){ //The length of user name is legal //Continue to determine whether there are illegal characters var regExp = /^[A-Za-z0-9]+$/; var ok = regExp.test(username); if(ok){ //The user name is finally legal usernameErrorSpan.innerText = "The user name is legal"; }else{ //The user name contains special symbols usernameErrorSpan.innerText = "The user name can only consist of numbers and letters"; } }else{ //Illegal user name length usernameErrorSpan.innerText = "User name length must be[6-14]between" } }else{ //Represents that username is an empty string usernameErrorSpan.innerText = "User name cannot be empty"; } //Other methods judged to be empty //if(username.length == 0) //if(username === "") } //Bind the focus event to the user name text box usernameElt.onfocus = function () { //Empty illegal value if(usernameErrorSpan.innerText != ""){//Whether the user name filled in is legal depends on whether span displays red font usernameElt.value = ""; } //Empty span usernameErrorSpan.innerText = ""; } //Get span label with wrong password var pwdErrorSpan = document.getElementById("pwdError"); //Get confirm password box object var userpwd2Elt = document.getElementById("userpwd2"); var userpwdElt = document.getElementById("userpwd"); userpwd2Elt.onblur = function () { //Get password and confirm password var userpwd = userpwdElt.value; var userpwd2 = userpwd2Elt.value; if(userpwd != userpwd2){ //Inconsistent passwords pwdErrorSpan.innerText = "Inconsistent passwords"; }else{ //Consistent password } } //Bind the focus event to the determined password userpwd2Elt.onfocus = function () { if(pwdErrorSpan.innerText != ""){ userpwd2Elt.value = ""; } pwdErrorSpan.innerText = ""; } //Bind blur event to email var emailElt = document.getElementById("email"); //Get email span var emailErrorSpan = document.getElementById("emailError"); emailElt.onblur = function () { //Get email var email = emailElt.value; //Write regular expressions for email var emailRegExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; var ok = emailRegExp.test(email); if(ok){ //email legal }else{ //email is illegal emailErrorSpan.innerText = "Illegal email address"; } } //Bind the focus event to email emailElt.onfocus = function () { if(emailErrorSpan.innerText != ""){ emailElt.value = ""; } emailErrorSpan.innerText = ""; } //Bind a mouse click event to a button var submitBtnElt = document.getElementById("submitBtn"); submitBtnElt.onclick = function () { //Trigger blue of username, blue of userpwd2, blue of email //No manual operation is required, and events are triggered with pure JS code usernameElt.focus(); usernameElt.blur(); userpwd2Elt.focus(); userpwd2Elt.blur(); emailElt.focus(); emailElt.blur(); //When all form items are legal, submit the form if(usernameErrorSpan.innerText == "" && pwdErrorSpan.innerText == "" && emailErrorSpan.innerText == "" && userpwdElt.value != ""){ //Get form object var userFormElt = document.getElementById("userForm"); //Submit Form userFormElt.submit(); } } } </script> <!--This form submission should use post,Here, for detection, we use get. --> <form id="userForm" action="http://localhost:8080/jd/save" method="get"> user name <input type="text" name="username" id="username"/> <span id="usernameError"></span> <br> password <input type="text" name="userpwd" id="userpwd"/><br> Confirm password <input type="text" id="userpwd2"/> <span id="pwdError"></span> <br> mailbox <input type="text" name="email" id="email"/> <span id="emailError"></span> <br> <!--<input type="submit" value="register"/> --> <input type="submit" value="register" id="submitBtn"/> <input type="reset" value="Reset"/> </form> </body> </html>
3.6 select all and deselect all check boxes
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Select all and deselect all check boxes</title> </head> <body> <script type="text/javascript"> window.onload = function () { var firstChk = document.getElementById("firstChk"); var aihaos = document.getElementsByName("aihao");//getElements gets an array firstChk.onclick = function () { for(var i = 0;i < aihaos.length;i++){ aihaos[i].checked = firstChk.checked;//checked property } } var all = aihaos.length; for(var i = 0;i < aihaos.length;i++){ aihaos[i].onclick = function () { //When the total quantity is equal to the selected quantity, the first check box is selected var checkedCount = 0; for(var i = 0;i < aihaos.length;i++){ if(aihaos[i].checked){//Number of boxes selected checkedCount++; } } //If the number of selected boxes is the same as the total number, all boxes will be selected automatically firstChk.checked = (all == checkedCount); /* if(all == checkedCount){ firstChk.checked = true; }else{ firstChk.checked = false; } */ } } } </script> <input type="checkbox" id="firstChk"/>Select all<br> <input type="checkbox" name="aihao" value="smoke"/>smoking<br> <input type="checkbox" name="aihao" value="drink"/>drink<br> <input type="checkbox" name="aihao" value="tt"/>Hot head </body> </html>
3.7 get the value of the selected item in the drop-down list
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Gets the name of the selected item in the drop-down list value</title> </head> <body> <script type="text/javascript"> window.onload = function () { var provinceListElt = document.getElementById("provinceList"); provinceListElt.onchange = function () { //Gets the value of the selected item alert(provinceListElt.value); } } </script> <select id="provinceList"> <option value="">--Please select a province--</option> <option value="001">Hebei Province</option> <option value="002">Henan Province</option> <option value="003">Shandong Province</option> <option value="004">Shanxi Province</option> </select> </body> </html>
3.8 display Web clock
JS built-in support class: Date. It can be used to obtain time / Date.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Show web clock</title> </head> <body> <script type="text/javascript"> //Get the current system time var nowTime = new Date(); //output //document.write(nowTime); //Convert to date format with locale. nowTime = nowTime.toLocaleString(); document.write(nowTime); document.write("<br>"); document.write("<br>"); //When the above format is not what you want, you can obtain information such as year, month and day through the date, and customize the date format var t = new Date(); var year = t.getFullYear();//Return year information in full format var month = t.getMonth();//The month is 0-11 //var dayOfWeek = t.getDay(); / / get the day of the week (0-6) var day = t.getDate();//Get date information document.write(year + "year" + (month + 1) + "month" + day + "day"); document.write("<br>"); document.write("<br>"); //Key point: how to obtain the number of milliseconds? (the total number of milliseconds from 00:00:00:000 on January 1, 1970 to the current system time) //var times = t.getTime(); //document.write(times); / / generally, the number of milliseconds is used as the timestamp document.write(new Date().getTime()); </script> <br><br> <script type="text/javascript"> function displayTime() { var time = new Date(); var strTime = time.toLocaleString(); document.getElementById("timeDiv").innerHTML = strTime; } var v; //The displayTime() function is called every 1 second function start(){ //From the end of this line of code, the displayTime() function will be called continuously every 1000 milliseconds v = window.setInterval("displayTime()",1000); } function stop() { //setInterval generates a return value that can be passed to clearInterval to cancel the periodic execution of code window.clearInterval(v); } </script> <input type="button" value="display system time" onclick="start();"/> <input type="button" value="System time stop" onclick="stop();"/> <div id="timeDiv"></div> </body> </html>
3.9 internal support class Array
Array. Note that the creation of the array is the brackets' [] '.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Built in support class Array</title> </head> <body> <script type="text/javascript"> /* //Create an array with length 0 var arr = []; alert(arr.length); //Arbitrary data type var arr2 = [1,2,3,false,"abc",3.14]; alert(arr2.length); //Does the subscript cross the line? arr2[7] = "test";//Automatic capacity expansion. If the middle subscript has no value, the value is automatically transferred undefined document.write("<br>"); //ergodic for(var i = 0;i < arr2.length;i++){ document.write(arr2[i] + "<br>"); } //Another way to create an object of an array var a = new Array();//Nothing is written to represent an empty array alert(a.length);//0 var a2 = new Array(3);//Write a number to represent the length of the array alert(a2.length);//3 var a3 = new Array(3,2);//Write multiple numbers to represent the elements in the array alert(a3.length);//2 */ var a = [1,2,3,9]; var str = a.join("-"); alert(str);//1-2-3-9 //Add an element at the end of the data (array length + 1) a.push(10); alert(a.join("-"));//1-2-3-9-10 //Pop up the element at the end of the array (array length - 1) var endElt = a.pop(); alert(endElt); alert(a.join("-")); //Note: the array in JS can automatically simulate the stack data structure: last in first out, first in first out //push stack //Pop pop stack //Invert array a.reverse(); alert(a.join("-"));//9-3-2-1 </script> </body> </html>
PS: sort out according to the power node course. If there is infringement, contact to delete it.