typora-copy-images-to: img
Today's content
-
JavaScript introduction
-
Basic syntax of JavaScript
-
JavaScript properties and text operations
-
Dom operation of JavaScript
I JavaScript introduction
1. JavaScript overview
JavaScript is a client-side scripting language. It is an object-based and event driven client-side scripting language, which can be run directly on the browser side.
-
Client: Browser
-
Scripting language: it can be run directly without compilation (as long as the browser is installed on the computer, javascript language can be run)
-
Object based: javascript has provided most objects, and front-end developers can directly use these objects (objects need not be created, but can be used directly)
-
Event driven: the javascript code bound to the event is driven by triggering the event to realize the dynamic effect of the web page.
-
The core function is to enhance the interaction between users and HTML pages and make the pages have some dynamic effects. To enhance the user experience!
2. Development history of JavaScript
-
In 1995, NetScape developed a client script language: LiveScript.
Later, experts from SUN company were invited to modify it and named it JavaScript.
-
In 1996, Microsoft copied JavaScript and developed JScript scripting language.
-
In 1997, ECMA (European Computer Manufacturers Association) formulated the standard of client script language: ECMAScript, which unifies the coding mode of all client script languages.
-
summary
1995 In, NetScape (Netscape )A client script language developed by the company: LiveScript. Later, please come SUN The experts of the company will modify it and name it as: JavaScript. 1996 Microsoft plagiarized JavaScript Developed JScript Scripting language. 1997 In, ECMA (European Association of computer manufacturers),Develop the standard of client script language: ECMAScript,The coding method of all client scripting languages is unified.
3. Relationship between JavaScript and Java
==Differences between JavaScript and java
-
JavaScript is a scripting language: it can run directly (in the browser) without compilation
-
Java is a programming language: compile first and then run (the compilation process depends on jvm)
-
JavaScript is an object-based scripting language: objects can be used directly without creating them
-
Java is an object-oriented programming language: objects must be created before they can be used
-
JavaScript is a weakly typed scripting language, which means that all types of JavaScript can be represented by var
For example: var num=10; var str=“hello”, var flag = true;
-
Java is a strongly typed programming language, which means that when defining variables, you must first determine the type, and then define variables.
For example: int num=10; String str=“hello”; boolean flag = true;
==Similarities between JavaScript and java
- The basic syntax of JavaScript and java definitions is very similar
- The way javaScript is written is very similar to the way java writes code
4.JavaScript composition
-
ECMAScript
It standardizes the basic syntax of javascript
-
DOM
document object model: document object model (a model composed of a series of document objects)
Function: operate marked documents (referring to xml or html documents)
-
BOM
browser object model: browser object model (a model composed of a series of browser objects)
Function: operate the browser.
5. Summary
-
javascript is a client-side scripting language
-
javascript is a weakly typed language (even if the syntax is not standardized sometimes, there is no error)
-
Three components of javascript = basic syntax + DOM+BOM
-
Common front-end development tools
Front end development tools: develop front-end code, such as HTML, CSS and JavaScript
- HBuilder (domestic development tool): powerful, easy to use, charging
- Vscade (non domestic development tool): powerful, easy to use, charged
- WebStom (non domestic development tool): powerful, not easy to use, charged
- Dreamweaver (non domestic development tool): not powerful and easy to use
Back end development tools: develop back-end code, of course, you can also develop front-end code (disadvantage: the completion function is not very good)
- Idea (integrated development tool): it is inconvenient to develop all languages and front-end languages
- Eclipse (integrated development tool): it is inconvenient to develop java language and front-end language
- MyEclipse (integrated development tool): it is inconvenient to develop java language and front-end language
- STS (spring tools suitable integrated development tool): it is inconvenient to develop java language and front-end language
II Basic syntax of JavaScript
1. Grammatical norms
- Case sensitive
- At the end of each line of code, a semicolon is recommended.
- Code writing format (it is recommended to keep consistent with the code writing format of java)
2. Introduction to JavaScript
-
Entry program
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> //1. Define variable num=10; var num = 10; //2. Pop up warning box alert(num); </script> </body> </html> Note: Writing js When you code, you must add<script> js code </script>
3. Two ways of combining JavaScript and html
-
Method 1: embed js code directly in html
Advantages: you can directly see the written js code
Disadvantages: js code and html tags are together, which is not convenient for later maintenance
<body> <script type="text/javascript"> //1. Define variable num=10; var num = 10; //2. Pop up warning box alert(num); </script> </body>
-
Method 2: import external js files
Step 1: define a js file first. Step 2: import the externally defined js file through the src attribute of the script tag
Advantages: it is convenient for later js code maintenance
outer.js:
//1. Define variable num=10; var num = 10010; //2. Pop up warning box alert(num);
Introduce in html pages: external js files
<script type="text/javascript" src="js/outer.js" ></script>
-
details
4.javascript comments
- It is basically the same as java annotations
- Single line comment: / / comment content
- Multiline comment: / * comment content*/
5. Five original types
-
The type of java is basically the same as that of javascript
-
There are two types in javascript
-
To judge the type of variable, you can use the keyword: typeof
-
Original type
- Number type: number type
- String type: string or character
- Null type: for example: define a variable, assign a value of null, var a = null;
- Undefined type: undefined type, for example: define a variable without assignment, var a;
- boolean type: indicates true or false
-
reference type
- Boolean type
- Number type
- String type
- wait
-
Code demonstration
<script type="text/javascript"> //1. Define number type var num=10; //1.1. Determine the type of num document.write(num+" : "+(typeof num)+"<hr/>") //2. Define string type var str="hello world"; //2.1 output to browser document.write(str+" : "+(typeof str)+"<hr/>"); //3. Define boolean type var flag =true; //3.1 output to browser document.write(flag+" : "+(typeof flag)+"<hr/>"); //4. Define null type var obj =null; //4.1 output to browser document.write(obj +" : "+(typeof obj )+"<hr/>"); //5. Define undefined type var und; //5.1 output to browser document.write(und+" : "+(typeof und)+"<hr/>"); </script>
-
6. Constants and variables
-
javascript is a weakly typed scripting language. When defining variables or constants, you don't need to specify the type, or you can use var, let, const
-
Define local variables, using the keyword: let
For example: let num=10;
It is recommended to put the let inside the method (or outside the method, not recommended)
//2. Definition method 1: function test1(){ //1. Define local variables let num =10; alert("test1:"+num); } //2.1 calling test1();
-
Define global variables,
Basic syntax: variable name = value / / variable name is a global variable. This is not recommended
<script type="text/javascript"> //1. Definition method 1: function test1(){ //1. Define global variables num =10; alert("test1:"+num); } //1.1 call test1(); //1. Definition method 1: function test2(){ alert("test2:"+num); } //1.1 call test2(); </script>
Suggested writing format:
var variable name A// Variable name A is the global variable
Variable name A = assignment
<script type="text/javascript"> //0. Use var to define global variables var num=null; //1. Definition method 1: function test1(){ //1. Define global variables num =10; alert("test1:"+num); } //1.1 call test1(); //1. Definition method 1: function test2(){ alert("test2:"+num); } //1.1 call test2(); </script>
-
Constant value (value that cannot be changed), keyword: const
<script type="text/javascript"> //1. Define a constant value const num =10; //2. Test console.log("Print constant values:"+num);//Correct writing console.log("Changing the value of a constant:"+(num++));//Wrong writing: cannot change the value of constant </script> Note: constant values can be defined inside or outside the method.
-
details
-
If you use the var keyword when defining variables: there is a promotion of type variables (directly: use first and then define)
-
If you define variables or constants, use the let or const keyword: there is no promotion of type variables
-
<script type="text/javascript"> //1.var defines variables. There is a case of type promotion // alert("undefined, use first" + a); // var a=10; // alert("use after definition" + a); //2. let defines variables. There is no type promotion alert("Undefined, cannot be used first"+b); let b=66; </script>
-
7. Operator
-
Arithmetic operator
Details:
If a number and a number of string type operate:
-
If it is a + sign, string splicing is performed
-
If it is not a + sign, it is an arithmetic operation
-
<script type="text/javascript"> var num = 10; var num2 = 20; console.log("Addition operation:"+(num+num2)); var str="66"; console.log("Operator and numeric 1 of string type:"+(num+str));//+No.: String splicing console.log("Operator and number 2 of string type:"+(num%str));//-Sign (* /%): Operation </script>
-
-
Assignment Operators
The details of the operator are the same as those of the arithmetic operator.
-
Comparison operator
Details:
==: only compare whether the values are the same
===: compare values and data types
-
Logical operator
be careful:
- Empty string inversion: true
- null Negation: true
- 0 reverse operation: true
- Nan inversion operation: true
-
Ternary operator
-
Scenario: data is paged, 100 pieces of data are displayed, 10 pieces are displayed on each page, and the total number of pages is calculated
-
//Scenario: data is paged, 100 pieces of data are displayed, 10 pieces are displayed on each page, and the total number of pages is calculated var totalCount=109; var pageSize=10; var totalPages = (totalCount%pageSize==0)? (totalCount/pageSize): Math.floor(totalCount/pageSize)+1; document.write(totalPages);
-
8. Process control statement
-
if statement
-
switch statement
-
for loop
-
while loop
-
Small exercise: 99 multiplication table
<script type="text/javascript"> document.write("<table border='0px' align='center'>") //1. Circular rows for (var i = 1; i <=9 ; i++) { //2. Columns of cycles document.write("<tr>") for (var j = 1; j <= i; j++) { document.write("<td style='border:1px solid blue;'>") document.write(i+"*"+j+"="+(i*j)+" ") document.write("</td>") } //3. Change line document.write("</tr>") } document.write("</table>") </script>
9. Array
-
Array creation:
-
Method 1: directly create an array of specified elements
var arr1 = [1,"a","b",true];
var arr2= new Array(1,"a","b",true);
-
Method 2: create an empty array
var arr1=[ ]; Or var arr2= new Array();
-
Method 3: create an array of specified length
Var arr = new array size (number)
-
-
Array features:
-
Element type of array: can be any type
-
The length of the array can vary
Length of array = maximum index value of array + 1
-
-
Properties of array:
- Length property: gets the length of the array
-
Array method:
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-x5ccowy-1641790802309) (IMG / image-20200707152734084. PNG)]
1.var str = array object Join (connection symbol)// character string
2.var endEle = array object pop();// Delete the last element and return
3.var lenght = array object push(ele);// Add an element ele to the end of the array and return the new length
- var arrNew = array object reverse();// Reverse the order of array elements and return a new array
10. Function
-
Function creation
-
Mode 1: dynamic function
Var fun1 = new function (parameter, method body);
-
Mode 2: ordinary function
function method name (parameter of the method){
Method body content
}
-
Method 3: anonymous function
var method name = function (parameter of the method){
Method body content
}
<script type="text/javascript"> //1. Dynamic function --- create (rarely used) var param = "a,b"; var method_body = "alert(a+b);"; var fun1 = new Function(param,method_body); //1.1 calling functions //fun1(10,20); //2. Ordinary function ---------- create function fun2(a,b) {//Parameters: a, b alert(a+b);//Method body } //2.1 calling function //fun2(1,5); //3. Anonymous function ---- create var fun3 = function(a,b){ alert(a+b); } //3.1 calling functions fun3(1,-8); </script>
-
-
Function call
Principles to be followed:
- Create function first
- Call the function again
- Attention to details: when defining parameters, VaR and let are not added in front of parameters
-
Properties of function
Get the number of parameters: length
var fun3 = function(a,b,c){ alert(a+b+c); } alert(typeof fun3) //3.1 calling functions alert("fun3 Number of parameters of method:"+fun3.length); fun3(1,-8,9);
be careful:
- When getting the number of parameters: function name length
- Calling function: function name (parameter);
11. Summary of basic grammar
- Comments: single line / / multiple lines/**/
- Input and output statements: prompt(), alert(), console log(),document.write()
- Variables and constants: let, const
- Data types: boolean, null, undefined, number, string, bigint
- typeof keyword: used to determine the data type of a variable
- Operators: arithmetic, assignment, logic, comparison, ternary operator
- Process control and loop statements: if, switch, for, while
- Array: there is no limit on data type and length. let array name = [length / element]
- Function: use similar methods to extract code and improve reusability
III Dom operation of JavaScript
1.Dom overview
DOM: Document Object Model document object model, function: to operate marked documents (xml and html documents learned at present)
Demonstrate the DOM operation process:
2.Dom classification
-
Core DOM (basic syntax of ECMA specification)
The api of core Dom operates XML and HTML
-
Dom of xml
Function: to manipulate xml documents
-
Dom of html
Function: to manipulate html documents
-
Summary:
Most APIs of core Dom, xml Dom and HTML Dom are universal.
3.Dom api
3.1 Dom operation label (crud label)
- Get label object:
-
Get tag object based on id: get a tag object
-
Get label object according to label name: multiple label objects are obtained
-
Get label objects according to the name attribute: multiple label objects are obtained
-
Get label object according to class attribute: multiple label objects are obtained
-
The code is as follows:
password:<input type="password" name="psw" /><br/> user name:<input type="text" name="username" id="uname" class="s" /><br/> Gender:<input type="radio" name="sex" class="s" value="man"/>male <input type="radio" name="sex" class="s" value="woman"/>female<br/> <script type="text/javascript"> //1. Obtain the label object according to the id var username_obj = document.getElementById("uname"); console.log("username Input box for:"+username_obj.id); //2. Get the tag object according to the attribute value of name var sex_objs = document.getElementsByName("sex"); console.log("sex Number of labels for attribute:"+sex_objs.length) //3. Get the tag object according to the attribute value of class var class_objs = document.getElementsByClassName("s"); console.log("class Number of labels for attribute:"+class_objs.length) //4. Obtain the label object according to the label name var tag_objs = document.getElementsByTagName("input"); console.log("input Number of labels for label name:"+tag_objs.length) </script>
- Operation label object (crud)
<center> <h1 id="h11">Primary title</h1> <a href="#"Id =" a11 "> a hyperlink</a> <div style="border: 1px solid blue;width: 200px;height: 100px;margin: auto;"></div> <input type="button" value="Add a label to div in" onclick="addH1();" /><br/> <input type="button" value="delete div Medium h1 label" onclick="deleteH1();" /><br/> <input type="button" value="hold h1 replace with a label" onclick="changeTag();" /><br/> <input type="button" value="Create a new label and add it to div in" onclick="createTag();" /><br/> </center> <script type="text/javascript"> //1. Add labels function addH1(){ //1. Get the tag object with id=h11 var h1_tag = document.getElementById("h11"); //2. Get div tag object var div_tag = document.getElementsByTagName("div")[0]; //3. Add the h1 tag to the div div_tag.appendChild(h1_tag);//Parent object AppendChild (child object) } //2. Delete label function deleteH1(){ //1. Get the tag object with id=h11 var h1_tag = document.getElementById("h11"); //2. Get div tag object var div_tag = document.getElementsByTagName("div")[0]; //3. Add the h1 tag to the div div_tag.removeChild(h1_tag);//Parent object Removechild (child object) } //3. Replace labels function changeTag(){ //1. Get h1 tag var h1_tag = document.getElementById("h11"); //2. Get a tag var a_tag = document.getElementById("a11"); //3. Get div tag var div_tag = document.getElementsByTagName("div")[0]; //4. Replace labels div_tag.replaceChild(a_tag,h1_tag); } //4. Create a new tag and add it to div function createTag(){ //1. Create a new a tag, attribute and text var a_tag = document.createElement("a"); //1.1 setting properties a_tag.setAttribute("href","demo1_Get label object.html"); //1.2 setting text a_tag.innerText="Point me,Go jump"; //2. Get div and add the new tag created document.getElementsByTagName("div")[0].appendChild(a_tag); } </script>
3.2 Dom operation attribute (set attribute, get attribute, remove attribute)
- method:
<a id="a1">Click me to jump</a> <a id="a2" href="#"> Click me to jump</a> <hr /> <br /> <input type="button" value="set a property" onclick="addAttr()" /> <input type="button" value="Remove Attribute " onclick="removeAttr()" /> <input type="button" value="get attribute" onclick="getAttr()" /> <input type="button" value="Method 2 of setting attributes" onclick="addAttr2()" /> <script type="text/javascript"> //4. Set attributes for a function addAttr2(){ //1. Get a tag object var a_tag = document.getElementById("a2"); //2. Set properties a_tag.style.textDecoration="none";//Usually: set css style to use } //1. Set a href = index html function addAttr(){ //1. Get a tag object var a_tag = document.getElementById("a1"); //2. Set properties a_tag.setAttribute("href","index.html"); } //2. Remove the href attribute of a tag function removeAttr(){ //1. Get a tag object var a_tag = document.getElementById("a1"); //2. Set properties a_tag.removeAttribute("href"); } //3. Get the href attribute of a tag function getAttr(){ //1. Get a tag object var a_tag = document.getElementById("a1"); //2. Set properties var str = a_tag.getAttribute("href"); alert(str); } </script>
3.3 Dom operation text (text: refers to the label body content)
-
Get text content
var text_content = label object innerText; // Label object innerHTML;
-
Set the text content (overwrite the original text content)
Label object innerText = "new text content";
Label object innerHTML = "new text content";
be careful:
- innerText property: parses plain text. Even labels are treated as plain text
- innerHTML attribute: it can parse plain text or labels
-
Note: the above operations must be on the containment label. Only the containment label has a label body.
-
<input type="text" name="username" id="ip" value="jack" /> <div id="d1"> I am a little bird!!! </div> <script type="text/javascript"> //1. Get label object var input_tag = document.getElementById("ip"); var input_text = input_tag.innerHTML;//Wrong writing. input has no label body console.log("input: "+ input_tag.value); //2. Get div var div_tag = document.getElementById("d1"); //2.1 get the content of the label body //var div_text= div_tag.innerHTML; var div_text = div_tag.innerText; console.log("div Label body:"+div_text); //2.2 setting the content of the label body //div_tag.innerText="<a href='#'>xxx</a>"; div_tag.innerHTML="<a href='#'>xxx</a>"; </script>