JavaScript:
Concept: a client scripting language
- Running in the client browser. Every browser has a JavaScript parsing engine
- Script language: it can be parsed and executed by the browser without compilation
Functions:
- It can enhance the interaction between users and html pages, control html elements, make the pages have some dynamic effects, and enhance the user experience.
History of JavaScript:
- In 1992, nobase company developed the first client-side scripting language, which is specially used for form verification. Named: C --, later: ScriptEase
- In 1995, Netscape developed a client-side scripting language: LiveScript. Later, an expert from SUN company was invited to modify LiveScript, named JavaScript
- In 1996, Microsoft copied JavaScript to develop JScript language
- In 1997, ECMA (European Association of computer manufacturers) formulated the standard of client-side scripting language: ECMAScript is to unify the coding methods of all client-side scripting languages.
- JavaScript = ECMAScript + something unique to JavaScript (BOM+DOM)
ECMAScript: the standard of client script language
1. Basic syntax:
- Combination with html
1. Internal JS: define < script >, and the content of label body is JS code
2. External JS: define < script > and import external JS file through src attribute
- Be careful:
- < script > can be defined anywhere on an html page. But the location of the definition affects the order of execution.
- < script > can define multiple.
- Notes
1. Single line comment: / / comment content
2. Multiline comment / comment content/
- Data type:
- Original data type (basic data type):
- Number: number. Integer / decimal / NaN(not a number is not a number type)
- String: string. String "abc", "a", "abc"
- boolean: true and false
- null: a placeholder with an empty object
- Undefined: undefined. If a variable has no initialization value, it will be assigned undefined by default
- Reference data types: objects
- Original data type (basic data type):
- variable
- Variable: a small amount of memory space for storing data
- Java is a strongly typed language, while JavaScript is a weakly typed language.
- Strong type: when the variable storage space is opened up, the data type of the data stored in the space in the future is defined. Only fixed type data can be stored
- Weak type: when the variable storage space is opened, the future storage data type of the space is not defined, and any type of data can be stored.
- Syntax: var variable name = initialization value;
- typeof operator: gets the type of the variable. (Note: object is obtained after null operation)
- operator
- Unary operator: operator with only one operand + +, -, + (positive sign)
- ++--: Auto increment (auto decrement) -- + + (–) before, auto increment (auto decrement), then operation, + + (–) after, first operation, then auto increment (auto decrement)
- +(-): Sign
- Note: in JS, if the operand is not the type required by the operator, the JS engine will automatically convert the operand to type
- Other types to number:
- string to number: convert by literal value. If the literal value is not a number, convert to NaN (not a number of numbers)
- boolean to number: true to 1, false to 0
- Arithmetic operators ------------ + - * /%
- Assignment operators -------- =, +, = - +
- Comparison operators --------- >, <, > =, < =, = =, = = (all equal to)
- Comparison mode
- Same type: direct comparison ------ string: compare in dictionary order. Compare bit by bit until you get the size.
- Different types: type conversion first, then comparison ------------ = = =: all equal. Before comparison, judge the type first. If the types are different, return false directly
- Comparison mode
- Logical operator - & & |!
Other types to boolean:
1. number: 0 or NaN is false, others are true
2. string: all are true except empty string ("")
3. Null & undefined: all false
4. Object: all objects are true (as long as they are not null) - Ternary operator
?: expression
var a = 3;
var b = 4;
var c = a > b ? 1:0;
Syntax:- Expression? Value 1: value 2;
- Judge the value of the expression. If it is true, the value is 1. If it is false, the value is 2;
- Unary operator: operator with only one operand + +, -, + (positive sign)
- Process control statement:
1. if...else...
2. switch:
*In java, the data types that can be accepted by switch statement: byte int short char, enumeration (1.5), string (1.7)
*Switch (variable):
case value:
*In JS, the switch statement can accept any raw data type
3. while
4. do...while
5. for
- JS special syntax:
- Statement ends with; if there is only one statement in a line; can be omitted (not recommended)
- The var keyword is used to define variables, or not
- Use: the defined variable is a local variable
- Not used: the defined variable is a global variable (not recommended)
6. Basic objects:
- Function: function object
- Establish:
- Var fun = new function; / / forget it
- function method name (list of formal parameters){
Method body
} - var method name = function (list of formal parameters){
Method body
}
- Method:
- Property: length: number of parameters
- Characteristic:
- The method definition is that the type of the parameter does not need to be written, nor does the return value type.
- Method is an object, if a method with the same name is defined, it will be overwritten
- In JS, the call of a method is only related to the name of the method, not to the parameter list
- In the method declaration, there is a hidden built-in object (array), arguments, which encapsulates all the actual parameters
- Call: method name (actual parameter list);
- Establish:
- Array: array object
- Establish:
- Var arr = new array (list of elements);
- Var arr = new array (default length);
- var arr = [element list];
- Method
- Join (parameter): splices the elements in the array into a string according to the specified separator
- push() adds one or more elements to the end of the array and returns the new length.
- Property: length: length of array
- Characteristic:
- In JS, the type of array element is variable.
- In JS, the array length is variable.
- Establish:
- Boolean
- Date: Date object
- Create: var date = new Date();
- Method:
toLocaleString(): returns the time local string format corresponding to the current date object
getTime(): gets the value of milliseconds. Returns the difference in milliseconds between the time described by the current scheduled object and zero on January 1, 1970
- Math: mathematical object
- Create: the Math object is not created, but directly used. Math. Method name ();
- Method:
random(): returns a random number between 0 and 1. Containing 0 does not contain 1.
ceil(x): round up the logarithm.
floor(x): round down the logarithm.
round(x): round a number to the nearest whole number. - Property: PI
- Number
- String
- RegExp: regular expression object
- Regular expression: defines the composition rules of a string.
- Single character: [] ------ for example: [a] [ab] [a-zA-Z0-9]
A single character representing a particular meaning:
\d: Single numeric character [0-9]
\w: Single word character [a-zA-Z0-9] - Quantifier symbols:
?: indicates 0 or 1 occurrence
*: indicates 0 or more occurrences
+: occurs 1 or more times
{m,n}: means m < = quantity < = n
*m if the default is: {, n}: n times at most
*n if the default is: {m,} at least m times - Start end symbol
* ^: start
* $: end
- Single character: [] ------ for example: [a] [ab] [a-zA-Z0-9]
- Regular object:
- Establish
- var reg = new RegExp("regular expression");
- var reg = / regular expression /;
- Method ----------- test (parameter): verify whether the specified string conforms to the specification of the regular definition
- Establish
- Regular expression: defines the composition rules of a string.
- Global
- Feature: Global object. The encapsulated method in Global can be called directly without object. Method name ();
- Method:
- encodeURI(): url encoding
- decodeURI(): url decoding
- Encodeuriccomponent(): URL encoding, encoding more characters
- Decodeuriccomponent(): URL decoding
- parseInt(): convert a string to a number -------- judge whether each character is a number one by one until it is not a number, and then
- isNaN(): judge whether a value is NaN ------ NaN six parents don't recognize it, even they don't recognize it. NaN participated in = = compare all asked false
- eval(): talk about JavaScript strings and execute them as script code.
- URL encoding
Podcasts for spreading wisdom =% E4%BC%A0%E6%99%BA%E6%92%AD%E5%AE%A2
DOM simple learning: to meet case requirements
Function: control the content of html document
Get page label (Element) object: Element
-
document.getElementById("id value"): get the element object through its id
-
To manipulate an Element object:
- Modify property value:
- What is the object of acquisition?
- Check the API documentation to find out which properties can be set
- Modify label body content: (attribute: innerHTML)
1. Get element object
2. Use the innerHTML attribute to modify the label body content
Event simple learning
- Function: after some components are executed some operations, trigger the execution of some code.
- How to bind events
- Directly on the html tag, specify the attribute (operation) of the event, and the attribute value is js code
- Event: onclick - click event
- Get the element object through js, specify the event attribute, and set a function
Code:
<body> <img id="light" src="img/off.gif" onclick="fun();"> <img id="light2" src="img/off.gif"> <script> function fun(){ alert('I was ordered.'); alert('I was ordered again'); } function fun2(){ alert('How can I get older?'); } //1. Get light2 object var light2 = document.getElementById("light2"); //2. Binding event light2.onclick = fun2; </script> </body>
Case 1: light switch
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Light switch</title> </head> <body> <img id="light" src="img/off.gif"> <script> /* Analysis: 1.Get picture object 2.Bind click event 3.Switch pictures every time you click * Rules: * If the light is on, switch the picture to off * If the light is off, switch the picture to on * Using flag to complete */ //1. Get picture object var light = document.getElementById("light"); var flag = false;//It means the light is off. Off pictures //2. Bind click event light.onclick = function(){ if(flag){//Judge if the light is on, it will be off light.src = "img/off.gif"; flag = false; }else{ //If the light is off, turn it on light.src = "img/on.gif"; flag = true; } } </script> </body> </html>
BOM:
1. Concept: Browser Object Model browser object model, which encapsulates all components of the browser into objects.
2. composition:
- Window: window object
- Navigator: Browser Object
- Screen: display screen object
- History: history object
- Location: address bar object
3. Window: window object
1. Create - see features
2. method
- Methods related to pop ups:
- alert(): displays a warning box with a message and a confirm button.
-
confirm(): displays a dialog box with a message and a confirm and Cancel buttons.
- If the user clicks the OK button, the method returns true
- If the user clicks the Cancel button, the method returns false
- prompt(): displays a dialog box that prompts for user input. -----------Return value: get the value entered by the user
- Methods related to opening and closing:
- close(): closes the browser window. ----------Who calls me? Who do I turn off
- open(): open a new browser Window -------- return a new Window object
- Timer related methods
-
setTimeout(): call a function or compute an expression after the specified millisecond count.
- Parameters:
- js code or method object
- Millisecond value
- Return value: unique identification, used to cancel the timer
- Parameters:
- clearTimeout(): cancels the timeout set by the setTimeout() method.
- setInterval(): calls a function or evaluates an expression in milliseconds over a specified period.
- clearInterval(): cancels the timeout set by setInterval().
-
setTimeout(): call a function or compute an expression after the specified millisecond count.
Case 2: rotation chart
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <img id="img" src="img/banner_1.jpg" alt="" width="100%"> <script> var number = 1; //Modify picture src properties function fun(){ var img = document.getElementById("img"); img.src = "img/banner_" + ++number + ".jpg" if(number == 3){ number = 0; } } setInterval(fun,3000); </script> </body> </html>
3. properties:
- Get other BOM objects:
history
location
Navigator
Screen: - Get DOM object
document
4. characteristics
- window objects do not need to be created and can be directly used by windows. window. Method name ();
- window references can be omitted. Method name ();
4. Location: address bar object
1. Create (get):
- window.location
- location
2. method:
- reload() reloads the current document. Refresh
3. attribute
- href set or return the full URL.
Case 3: Auto jump:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> span{ color: red; } p{ text-align: center; } </style> </head> <body> <P><span id="time">5</span>Seconds later, jump to page.......</P> <script> var sencond = 5; var time = document.getElementById("time"); function showTime(){ time.innerHTML = --sencond + ""; if(sencond<=0){ location.href = "https://www.baidu.com"; clearInterval(a); } } var a = setInterval(showTime,1000); </script> </body> </html>
5. History: history object
1. Create (get):
- window.history
- history
2. method:
- back() loads the previous URL in the history list.
- forward() loads the next URL in the history list.
- Go loads a specific page in the history list.
Parameters:- Positive number: Several Historical Records
- Negative: back several history records
3. properties:
- length returns the number of URL s in the current window history list.
DOM:
Concept: Document Object Model
- The components of markup language document are encapsulated as objects. These objects can be used to perform CRUD dynamic operations on markup language documents
As shown in the figure below:
The W3C DOM standard is divided into three different parts:
- Core DOM - standard model for any structured document
- Document: document object
- Element: element object
- Attribute: attribute object
- Text: text object
- Comment: comment object
- Node: node object, other 5 parent objects
- XML DOM - standard model for XML documents
- HTML DOM - standard model for HTML documents
- Core DOM model:
-
Document: document object
- Create (get): in the html dom model, you can use the window object to get
- window.document
- document
- Method:
- Get Element object:
- getElementById(): get the element object according to the id attribute value. The id attribute value is generally unique
- getElementsByTagName(): get the element objects according to the element name. The return value is an array
- getElementsByClassName(): get the element objects according to the Class attribute value. The return value is an array
- getElementsByName(): get the element objects according to the value of the name attribute. The return value is an array
- Create additional DOM objects:
- createAttribute(name)
- createComment()
- createElement()
- createTextNode()
- Get Element object:
- attribute
- Create (get): in the html dom model, you can use the window object to get
-
Element: element object
- Get / create: get and create through document
- Method:
- Removeaattribute(): delete attribute
- setAttribute(): set attribute
- Node: node object, other 5 parent objects
- Feature: all dom objects can be considered as a node
- Method:
CRUD dom tree:- appendChild(): adds a new child to the end of the node's child list.
- removeChild(): deletes (and returns) the specified child of the current node.
- replaceChild(): replaces a child node with a new one.
- Property: parentNode returns the parent of the node.
-
Document: document object
Case 4 - dynamic table
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Dynamic form</title> <style> table{ border: 1px solid; margin: auto; width: 500px; } td,th{ text-align: center; border: 1px solid; } div{ text-align: center; margin: 50px; } </style> </head> <body> <div> <input type="text" id="id" placeholder="Please enter the number"> <input type="text" id="name" placeholder="Please enter a name"> <input type="text" id="gender" placeholder="Please enter gender"> <input type="button" value="Add to" id="btn_add"> </div> <table id="table"> <caption>Student information form</caption> <tr> <th>number</th> <th>Full name</th> <th>Gender</th> <th>operation</th> </tr> <tr> <td>1</td> <td>Linghu Chong</td> <td>male</td> <td><a href="javascript:void(0)" onclick="delTr(this)">delete</a></td> </tr> <tr> <td>2</td> <td>Ren Woxing</td> <td>male</td> <td><a href="javascript:void(0)" onclick="delTr(this)">delete</a></td> </tr> <tr> <td>3</td> <td>Yue buqun</td> <td>?</td> <td><a href="javascript:void(0)" onclick="delTr(this)">delete</a></td> </tr> </table> <script> var btn_add = document.getElementById("btn_add"); btn_add.onclick = function(){ var id = document.getElementById("id").value; var name = document.getElementById("name").value; var gender = document.getElementById("gender").value; var td_id = document.createElement("td"); var text_id = document.createTextNode(id); td_id.appendChild(text_id); var td_name = document.createElement("td"); var text_name = document.createTextNode(name); td_name.appendChild(text_name); var td_gender = document.createElement("td"); var text_gender = document.createTextNode(gender); td_gender.appendChild(text_gender); var td_a = document.createElement("td"); var a = document.createElement("a"); a.setAttribute("href","javascript:void(0);"); a.setAttribute("onclick","delTr(this)"); text_a = document.createTextNode("delete"); a.appendChild(text_a) td_a.appendChild(a); var tr = document.createElement("tr"); tr.appendChild(td_id); tr.appendChild(td_name); tr.appendChild(td_gender); tr.appendChild(td_a) var table = document.getElementById("table"); table.appendChild(tr) } function delTr(obj){ var table = obj.parentNode.parentNode.parentNode; var tr = obj.parentNode.parentNode table.removeChild(tr) } </script> </body> </html>
- HTML DOM
- Setting and obtaining of tag body: innerHTML
- Using the properties of an html element object
- Control element styles
- Use the style attribute of the element to set, such as:
//Modify style mode 1
div1.style.border = "1px solid red";
div1.style.width = "200px";
//font-size–> fontSize
div1.style.fontSize = "20px"; - Define the style of the class selector in advance, and set its class attribute value through the className attribute of the element.
- Use the style attribute of the element to set, such as:
Event monitoring mechanism:
Concept: some components are executed some operations, trigger the execution of some code.
-
Event: some actions. For example: click, double-click, keyboard pressed, mouse moved
-
Event source: component. For example: button text input box
-
Listener: code.
-
Register listening: combine event, event source and listener together. When an event occurs on the event source, the execution of a listener code is triggered.
-
Common events:
- Click event:
- onclick: click event
- ondblclick: double click event
- Focus events
- onblur: lose focus -- commonly used for form validation
- onfocus: element gets focus.
- Load event:
- onload: a page or an image is loaded.
- Mouse events:
- onmousedown mouse button is pressed. -----0, 1, 2 (left key, scroll wheel, right key)
- When defining a method, define a parameter and accept the event object.
- The button attribute of the event object can be obtained by clicking the mouse button.
- onmouseup the mouse button is released.
- The onmousemove mouse is moved.
- onmouseover mouse over an element.
- onmouseout mouse moves away from an element.
- onmousedown mouse button is pressed. -----0, 1, 2 (left key, scroll wheel, right key)
- Keyboard events:
- onkeydown a keyboard key is pressed. --------------keycode==13 (enter)
- onkeyup a keyboard key is released.
- onkeypress a keyboard key is pressed and released.
- Selection and change
- The content of the onchange field is changed. ------------Commonly used in drop-down lists
- onselect text is selected.
- Form event:
-
onsubmit confirm button is clicked
You can block the submission of the form -------- if the method returns false, the form will be blocked from submission. - The onreset button is clicked.
-
onsubmit confirm button is clicked
Select all forms of case 5
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Form selection</title> <style> table { border: 1px solid; width: 500px; margin-left: 30%; } td, th { text-align: center; border: 1px solid; } div { margin-top: 10px; margin-left: 30%; } </style> </head> <body> <table> <caption>Student information form</caption> <tr> <th><input type="checkbox" id="all"></th> <th>number</th> <th>Full name</th> <th>Gender</th> <th>operation</th> </tr> <tr> <td><input type="checkbox" class="cb"></td> <td>1</td> <td>Linghu Chong</td> <td>male</td> <td><a href="javascript:void(0);" class="cb">delete</a></td> </tr> <tr> <td><input type="checkbox" class="cb"></td> <td>2</td> <td>Ren Woxing</td> <td>male</td> <td><a href="javascript:void(0);">delete</a></td> </tr> <tr> <td><input type="checkbox" class="cb"></td> <td>3</td> <td>Yue buqun</td> <td>?</td> <td><a href="javascript:void(0);">delete</a></td> </tr> </table> <div> <input type="button" id="selectAll" value="All election"> <input type="button" id="unSelectAll" value="Totally unselected"> <input type="button" id="selectRev" value="Reverse election"> <script> window.onload = function () { var selectAll = document.getElementById("selectAll"); selectAll.onclick = seltAll; var unSelectAll = document.getElementById("unSelectAll"); unSelectAll.onclick = unSelAll var selectRev = document.getElementById("selectRev"); selectRev.onclick = selRev document.getElementById("all").onclick = function () { var cbs = document.getElementsByClassName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = this.checked; }; } function seltAll() { var cbs = document.getElementsByClassName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = true; } var all = document.getElementById("all") if (!all.checked) { all.checked = true } } function unSelAll(){ var cbs = document.getElementsByClassName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = false; } var all = document.getElementById("all") if (all.checked) { all.checked = false } } function selRev(){ var cbs = document.getElementsByClassName("cb"); for (var i = 0; i < cbs.length; i++) { cbs[i].checked = !cbs[i].checked } var all = document.getElementById("all") if (all.checked) { all.checked = false; } } } </script> </div> </body> </html>
Case 6 - form validation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Registration page</title> <style> * { margin: 0px; padding: 0px; box-sizing: border-box; } body { background: url("img/register_bg.png") no-repeat center; padding-top: 25px; } .rg_layout { width: 900px; height: 500px; border: 8px solid #EEEEEE; background-color: white; /*Center the div horizontally*/ margin: auto; } .rg_left { /*border: 1px solid red;*/ float: left; margin: 15px; } .rg_left>p:first-child { color: #FFD026; font-size: 20px; } .rg_left>p:last-child { color: #A6A6A6; font-size: 20px; } .rg_center { float: left; /* border: 1px solid red;*/ } .rg_right { /*border: 1px solid red;*/ float: right; margin: 15px; } .rg_right>p:first-child { font-size: 15px; } .rg_right p a { color: pink; } .td_left { width: 100px; text-align: right; height: 45px; } .td_right { padding-left: 50px; } #username, #password, #email, #name, #tel, #birthday, #checkcode { width: 251px; height: 32px; border: 1px solid #A6A6A6; /*Set border fillet*/ border-radius: 5px; padding-left: 10px; } #checkcode { width: 110px; } #img_check { height: 32px; vertical-align: middle; } #btn_sub { width: 150px; height: 40px; background-color: #FFD026; border: 1px solid #FFD026; } #td_sub { padding-left: 150px; } .error { color: red; } </style> <script> /* Analysis: 1.Bind the onsubmit event to the form. The listener judges the result of each method verification. If both are true, the listener method returns true If one is false, the listener method returns false 2.Define some methods to verify each form item separately. 3.Bind the onblur event to each form item. */ window.onload = function () { //1. Bind the onsubmit event to the form document.getElementById("form").onsubmit = function(){ //Call the user verification method chekUsername(); return chekUsername() } document.getElementById("username").onblur = chekUsername //Verify user name function chekUsername(){ //1. Get the value of user name var username = document.getElementById("username").value //2. Define regular expression var reg_username = /^\w{6,12}$/ var s_username = document.getElementById("s_username") //3. Judge whether the value conforms to the regular rule var flag = reg_username.test(username); if(flag){ //Prompt green tick s_username.innerHTML = "<img width='35' height='25' src='img/gou.png'/>" }else{ s_username.innerHTML = "Incorrect format of user name!!" } return flag; } } </script> </head> <body> <div class="rg_layout"> <div class="rg_left"> <p>New user registration</p> <p>USER REGISTER</p> </div> <div class="rg_center"> <div class="rg_form"> <!--Define form form--> <form action="#" method="GET" id="form"> <table> <tr> <td class="td_left"><label for="username">User name</label></td> <td class="td_right"><input type="text" name="username" id="username" placeholder="enter one user name"> <span class="error" id="s_username"></span> </td> </tr> <tr> <td class="td_left"><label for="password">Password</label></td> <td class="td_right"><input type="password" name="password" id="password" placeholder="Please input a password"> </td> </tr> <tr> <td class="td_left"><label for="email">Email</label></td> <td class="td_right"><input type="email" name="email" id="email" placeholder="Please enter email"></td> </tr> <tr> <td class="td_left"><label for="name">Full name</label></td> <td class="td_right"><input type="text" name="name" id="name" placeholder="Please enter a name"> </td> </tr> <tr> <td class="td_left"><label for="tel">Cell-phone number</label></td> <td class="td_right"><input type="text" name="tel" id="tel" placeholder="Please enter your mobile number"></td> </tr> <tr> <td class="td_left"><label>Gender</label></td> <td class="td_right"> <input type="radio" name="gender" value="male"> male <input type="radio" name="gender" value="female"> female </td> </tr> <tr> <td class="td_left"><label for="birthday">Date of birth</label></td> <td class="td_right"><input type="date" name="birthday" id="birthday" placeholder="Please enter the date of birth"> </td> </tr> <tr> <td class="td_left"><label for="checkcode">Verification Code</label></td> <td class="td_right"><input type="text" name="checkcode" id="checkcode" placeholder="Please enter the verification code"> <img id="img_check" src="img/verify_code.jpg"> </td> </tr> <tr> <td colspan="2" id="td_sub"><input type="submit" id="btn_sub" value="register"></td> </tr> </table> </form> </div> </div> <div class="rg_right"> <p>Existing accounts?<a href="#">Login immediately</a></p> </div> </div> </body> </html>