1. What is JavaSpript
1.1 Overview
javaSpript is one of the most popular scripting languages in the world
A qualified backend must be javaScript proficient
1.2 History
Introduction: https://blog.csdn.net/kese7952/article/details/79357868
ECMAScript: A standard that can be understood as javaScript
The latest version has reached es6~but most browsers are still stuck with es5-enabled code!
Development Environment - Online Environment, Version Inconsistent
2. Quick Start
2.1 Introducing JavaScript
1. Intrinsic Introduction
inside 🏷️
<script> alert('Hello World'); </script>
2. External introduction
javascript block
alert('Hello World');
html block
<!DOCTYPE html> <html lang="en"> <head> <meta charset='utf-8'> <title>script</title> <script src='path Route'></script> </head> <body> <!--<script>--> <!-- alert('Hello World');--> <!--</script>--> <!--No definition, default is javascript--> <!-- <script type="text/javascript"></script> --> </body> </html>
2.2 Introduction to Basic Grammar
// variable var num=10; var name="konan"; alert(num); //Conditional control if(num>8){ alert(num+"This is num"); }else{ alert("This is not num") }
console.log(num)//value suot of output variable in console
Using the debugging platform of the browser:
2.3 Data Types
Numeric, Text, Graphics, Audio, Video...
number
js does not distinguish between decimal and integer
123 //Integer 123 123.4 //Decimal 123.4 1.234e5 //Scientific Counting -99 //negative NaN //not a number Infinity //Indicates infinity
Character string
'abcd' "abcde"
Boolean Value
true false
console.log(1>3) > false
Logical operation
&& || !
Comparison operator
= == Equal to (different types, same values, result is true) === Absolutely equal (same type, same value, result is true)
-
One drawback of js, insist not to use==comparison
-
NaN===NaN (false), NaN is not equal to all values, including yourself
-
A number can only be determined by isNaN(NaN)
Floating point problem:
Math.abs(1/3-(1-2/3))<0.00001 > true console.log(1/3) === (1-2/3) //Avoid this writing and the result is false > false
null and undefined
- null empty
- Undefined undefined
array
java values must be of the same type, not required in js
//Use [] whenever possible to improve readability var arr = [1,3,4,'konan',null,true] new Array(1,3,4,'konan',null,true)
Take the array subscript if it crosses the boundary:
> undefined
object
Objects are bracketed, arrays are bracketed~
Each property is separated by commas, and the last one does not need to be added
- Definition
var person = { name:"konan", age:3, tags:['js','java','mysql','web','...'] }
- Take the value of an object
person.name > "konan" person.tags[2] > "mysql"
2.4 Strict Check Mode
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- Prerequisite: IEDA Support needs to be set up ES6 grammar 'use strict':Enable strict inspection mode to prevent Javascript Some problems arise from the arbitrariness of Must be written in Javascript First line! Local variable recommendation let Define --> </head> <body> <script> 'use strict' // i=10 global variables let i=10; //ES6 let </script> </body> </html>
3. Data Types
3.1 String
- Wrap in single or double quotes
var msg='Student'; Var tar="Student";
- Escape Character\
\' \n \t \u4e2d Unicode character \u#### > in \x41 ASCII Character 0~255 > A
- Multiline character writing using ``package
let msg=`Hello Hello konan`; console.log(msg);
- Template String
let name='konan'; let age='18'; let msg2=`How do you do ${name}`; //Use ``Package to take effect console.log(msg2); > "How do you do konan"
- String Inmutability
let stu="Student"; console.log(stu[1]); > t stu[1]='R'; console.log(stu); > Student
- correlation method
let ch="Student"; console.log(ch.length); //Length 7 console.log(ch.toUpperCase()); //Uppercase STUDENT console.log(ch.toLowerCase()); //To lower case student console.log(ch.indexOf('d')); //Get Subscript 3 console.log(ch.substring(0,3)); //Intercept String [0,3] Stu
3.2 Array
Definition
var arr=[1,2,3,4,5]; arr[0]; arr[0]=1;
common method
arr.lenght //Return Length > 5 ⚠️give arr.length Assignment changes the size of the array. Assignment is too small, elements are lost, and voids are filled too large
arr.indexOf(2) //Obtain subscript index from element > 1 ⚠️String"1"Unlike number 1
arr.slice(1,3) //Intercepts part of arr and returns a new array, similar to subString in String > [2, 3]
arr.sort() //sort ['a','c','b'] arr.sort() ['a','b','c']
arr.reverse() //Element inversion > [5, 4, 3, 2, 1]
arr.concat(['A','B','C']) //Stitching Array > [1, 2, 3, 4, 5, "A", "B", "C"] ⚠️concat()The array was not modified, but a new one was returned
arr.join('-') //Separate array elements with specified connectors > "1-2-3-4-5"
arr.push('konan','Xiao Ming') //Push element to tail > [1, 2, 3, 4, 5, "konan", "Xiao Ming"] arr.pop() //An element at the end of the pop-up > [1, 2, 3, 4, 5, "konan"]
arr.unshift('ppsn') //Press element to head > ["ppsn", 1, 2, 3, 4, 5] arr.shift() //An element of the pop-up head > [1,2,3,4,5]
Multidimensional Array
arr=[[1,2],[5,'6'],['konan',10]] //Definition arr[2][0] //Visit > "konan"
3.3 Objects
Several key-value pairs, all keys in js are strings, values are arbitrary objects
//Define a person object that has four properties: var person={ name:'konan', age:18, email:'notre1024@163.com', score:0 }
1. Object Assignment
person.name = "konan2" person.name > konan2
2. Use a non-existent property without error
person.age > 18 person.gender > undefined
3. Dynamic Attribute Deletion
delete person.name > true person > {age: 18, email: "notre1024@163.com", score: 0}
4. Add dynamically, add values to new attributes directly
person.gender='male' person > {name: "konan", age: 18, email: "notre1024@163.com", score: 0, gender: "male"}
5. Determine whether the attribute value is in this object
'age' in person > true 'toString' in person > true //inherit
6. Determine if an attribute is owned by the object itself
person.hasOwnProperty('email2') > false person.hasOwnProperty('email') > true
3.4 Conditional Control
if...else
while / do...while
for
forEach
for...in
var a=[2,4,6,8,10,33,'konan']; //Traverse the array for (let i=0;i<a.length;i++){ console.log(a[i]); } a.forEach(function (value) { console.log(value); }) for (let i in a) { //Get Index console.log(a[i]); }
3.4 Map and Set
- Map: A collection of key-value pairs
var map=new Map([['konan1',88],['konan2',96],['konan3',99]]); var name=map.get('konan2'); map.set('konan3',79); map.set('admin',88); map.delete('konan1');
- Set: Unordered, non-repeating collection
let set=new Set([2,2,2,4,6,8,16]); set.add(1024); set.delete(4); console.log(set.has(16));
3.5 Iterable
foreach
var arr=[2,4,6,7,9,12]; for(let i of arr){ console.log(i); }
Traversing Map s
var map=new Map([['konan1',88],['konan2',96],['konan3',99]]); for(let x of map){ console.log(x); }
Traverse Set
var set=new Set([2,2,2,4,6,8,16]); for(let x of set){ console.log(x); }
4. Functions
4.1. Define Functions
Definition 1
function abs(x){ if(x>0){ return x; }else{ return -x; } }
Definition 2
var abs=function(x){ if(x>0){ return x; }else{ return -x; } }
Call function
abs(10); abs(-10);
Parameter problem: javaScript can pass any parameter or not to
var abs=function(x){ if(typeof x!=='number'){ //Throw an exception when the parameter is empty throw 'Not a Number'; } if(x>=0){ return x; }else{ return -x; } }
arguments
arguments is a free JS keyword that contains all the parameters passed in and is an array!
var abs=function(x){ console.log("x->"+x); for(var i=0;i<arguments.length;i++){ console.log(arguments[i]); } if(x>=0){ return x; }else{ return -x; } }
rest
Gets all parameters except those defined to form an array
function abc(a,b,...rest){ console.log("a->"+a); console.log("b->"+b); console.log(rest); } ⚠️rest Parameters can only be written at the end and must be used`...rest`Identification
Scope of 4.2 Variables
local variable
Declares in the body that functions are not available outside the body and that internal variables (closures can be used)
function abc(){ var x=1; x=x+1; } x=x+1; //[Error] ReferenceError: Can't find variable: x
Variables within a function do not conflict
function abc(){ var x=1; x=x+1; } function abc2(){ var x='A'; x=x+'B'; }
Internal functions can access members of external functions or vice versa
function abc(){ var x=1; function abc2(){ var y=x+1; //2 } var z=y+1; //ReferenceError: Can't find variable: y }
Duplicate names of internal and external variables
function abc(){ var x='A'; function abc2(){ var x='B'; console.log('inner'+x); //innerB } console.log('outer'+x); //outerA abc2(); } abc(); ⚠️Variables with the same name: Internal functions block variables of external functions
Promote the scope of a variable
function abc(){ var x='A'+y; //y is implicitly declared, but has no value. This is not recommended and is recommended to be defined in the header console.log(x); > xundefined y='B'; }
function abc(){ var x=1, y=x+1, z,i,a; } //Define variables in this form
Global Functions
var x=1; function abc(){ console.log(x); } abc(); console.log(x);
Global object window
var x='abc'; alert(x); alert(window.x); //All global variables are automatically bound to the window object by default console.log(window.x); window.alert(x); //alert itself is a window variable var old_alert=window.alert; old_alert(x); //old_alert is now equivalent to alert window.alert=function(){ }; window.alert('abc'); //This will invalidate window.alert=old_alert; //recovery window.alert('abcabc');
Standard
Since all global variables are bound to window s, conflicts can occur if different js files use the same global variables
//Unique global variable var konan = {}; //Define global variables konan.name = 'こなん'; konan.age = 18; konan.add = function(a,b){ //Define the method bound to the unique global variable name return a+b; } //Understanding jQuery
Local scope let
function abc(){ for(var i=0;i<100;i++){ console.log(i); } console.log(i+1); //101 }
//ES6 keyword, resolving local variable scope conflicts function abc(){ for(let i=0;i<100;i++){ console.log(i); } console.log(i+1); //i was not recognized and an error was thrown }
Constant const
Before ES6, define constants in uppercase letters
var PI=3.14; //Can be modified at will conosle.log(PI);
ES6 introduces the constant keyword const
const PI=3.14; console.log(PI); PI=124; //Error, not modifiable
4.3 Method
Definition method
var konan={ name:"こなん", birth:2003, //Method age:function (){ let now=new Date().getFullYear(); return now-this.birth; //this defaults to the object calling it } } console.log(konan.name); console.log(konan.age());//Access methods must be parenthesized ()
//Method function getAge(){ let now=new Date().getFullYear(); return now-konan.birth; //Can't use this } var konan={ name:"こなん", birth:2003, age:getAge }
apply
this can be controlled in js
//Method function getAge(){ let now=new Date().getFullYear(); return now-this.birth; //this defaults to the object calling it } var konan={ name:"こなん", birth:2003, age:getAge } getAge.apply(konan,[]); //Set this to point to konan with an empty parameter
5. Internal Objects
Standard object
typeof 123 < "number" typeof 'konan' < "string" typeof true < "boolean" typeof NaN < "number" typeof [] < "object" typeof {} < "object" typeof Math.abs < "function" typeof undefined < "undefined"
5.1 Date
Basic Use
var now = new Date(); //Sun Feb 06 2022 13:03:19 GMT+0800 (CST) Greenwich Time now.getFullYear(); //year now.getMonth(); //Month 0-11 now.getDate(); //day now.getDay(); //0-6 weeks now.getHours(); //time now.getMinutes(); //branch now.getSeconds(); //second ⚠️All values obtained are now Value at initialization in, now.getTime(); //time stamp console.log(new Date(now.getTime())); //Time stamp to time now.toLocaleString(); //"2022/2/6 1:03:19 PM" (call is a method, not a property) now.toGMTString(); //"Sun, 06 Feb 2022 05:03:19 GMT"
5.2 JSON
What is json
-
Lightweight Data Exchange Format
-
Until the advent of JSON, people used XML to transfer data. Because XML is a plain text format, it is suitable for exchanging data over a network.
-
In JavaScript, we can use JSON directly because JavaScript has built-in JSON resolution
-
Turning any JavaScript object into JSON means serializing the object into a JSON-formatted string that can be passed over the network to other computers. If we receive a JSON-formatted string, we can use it directly in JavaScript by deserializing it into a JavaScript object.
-
JSON is an effective format for Ajax applications because it allows quick conversion between JavaScript objects and string values JSON is a syntax for passing objects
-
Object with {}
-
Array with []
-
All key-value pairs use key:value
//Conversion of JSON and JS Objects var user = { name:"konan", age:19, sex:"male" } //stringify converts js objects into strings that conform to the json standard var jsonUser = JSON.stringify(user); //parse converts json-compliant strings into js objects var strUser = JSON.parse('{"names":"konan","age":19,"sex":"male"}'); ⚠️Use single quotation marks outermost
Differences between JSON objects and JS objects
var js = {names:"konan",age:19,sex:"male"}; var json = '{"names":"konan","age":19,"sex":"male"}';
-
6. Object-oriented programming
Prototype object
JavaScript does not distinguish between the concepts of classes and instances, but rather implements object-oriented programming through prototype s.
var Studnet={ name:"konan", age:19, run:function(){ console.log(this.name + ' is running...'); } } var xiaoming=function (){ name="xiaoming" } xiaoming.__proto__=Studnet; //Pointing the prototype of xiaoming to object Student is equivalent to inheriting Student xiaoming.name; // 'Xiao Ming' xiaoming.run(); // Xiao Ming is running... ⚠️Do not use directly obj.__proto__To change the prototype of an object
create Create Object
// Prototype object: var Student = { name: 'Robot', height: 1.2, run: function () { console.log(this.name + ' is running...'); } }; function createStudent(name) { // Create a new object based on the Student prototype: var s = Object.create(Student); // Initialize a new object: s.name = name; return s; } var xiaoming = createStudent('Xiao Ming'); xiaoming.run(); // Xiao Ming is running... xiaoming.__proto__ === Student; // true
function Student(props) { this.name = props.name || 'anonymous'; // The default value is'anonymous' this.grade = props.grade || 1; // Default value is 1 } Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); }; function createStudent(props) { return new Student(props || {}) } //The createStudent() function has several great advantages: //One is that you do not need new to call, the other is that the parameters are very flexible and can be passed without or like this: var xiaoming = createStudent({ name: 'Xiao Ming' }); xiaoming.grade; // 1
Create prototype-based JavaScript objects with new
function Student(name) { this.name = name; } //Add a new method to Student Student.prototype.hello = function () { alert('Hello, ' + this.name + '!'); };
class Inheritance
class keyword, introduced in ES6
- Define a class, property, method
//Define a student class class Student{ //constructor constructor(name){ this.name=name; } hello(){ alert('hello,js!'); } } var konan1=new Student('konan01');
- inherit
class pupil extends Student{ constructor(name,grade){ super(name); this.grade=grade; } mygrade(){ alert('I am a pupil!'); } } var konan2=new pupil('konan02',6);
7. Operating BOM Objects
window
Window represents browser window
window.alert('konan') > undefined window.innerHeight //Variable size > 206 window.innerWidth > 574 window.outerHeight //Browser Fixed Size > 945 window.outerWidth > 574
Navigator (not used)
Navigator encapsulates information about the browser
navigator.appVersion > "5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Safari/605.1.15" navigator.userAgent > "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Safari/605.1.15" navigator.platform > "MacIntel" ⚠️Not recommended and will be modified artificially
screen
Screen represents screen size
screen.width > 1512 screen.height > 982
location (important)
location represents URL information for the current page
location.protocol; // 'http' location.host; // 'www.example.com' location.port; // '8080' location.reload(); //Refresh Web Page location.assign('https://www.taobai.com'; // Open a new page
document
Doument represents the current page, HTML DOM document tree
document.title > "Baidu once, you know" document.title="konan" > "konan"
Get the node of the document tree
<body> <dl id="drink-menu" style="border:solid 1px #ccc;padding:6px;"> <dt>Mocha</dt> <dd>Hot Mocha</dd> <dt>Yoghurt</dt> <dd>Beijing Old Yoghurt</dd> <dt>fruit juice</dt> <dd>apple juice</dd> </dl> <script> 'use strict'; var menu = document.getElementById('drink-menu'); var drinks = document.getElementsByTagName('dt'); var i, s; s = 'The drinks provided are:'; for (i=0; i<drinks.length; i++) { s = s + drinks[i].innerHTML + ','; } console.log(s); </script> </body>
Get cookie s
document.cookie //Cookie read to current page > "BA_HECTOR=050421a40l2l81ah461gvveoi0q; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; H_PS_PSSID=35104_31253_34584_35490_35246_35801_35796_35326_26350_35746; BD_HOME=1; BD_UPN=143254; BDRCVFR[d9MwMhSWl4T]=mk3SLVN4HKm; PSINO=6; delPer=0; BD_CK_SAM=1; H_PS_645EC=cb17ETBVBlUO40la9pIbC3%2BWoSq2gIjodJD1Lfe%2BqJfn80GmSk%2B4DgPutTK%2BO7gletMugw; __sec_t_key=1b231dcf-9da2-4122-b1b6-54677291bdbf; BIDUPSID=F3BD1FFBA8A3915F2149A73D7A506D55; PSTM=1643964514; BAIDUID=F3BD1FFBA8A3915F2149A73D7A506D55:FG=1"
Since JavaScript can read Cookies on pages, and users'login information usually also exists in Cookies, this poses a huge security risk because it is allowed to introduce third-party JavaScript code into HTML pages:
<!-- The current page is on the wwwexample.com --> <html> <head> <script src="http://www.foo.com/jquery.js"></script> </head> ... </html>
If malicious code exists in the introduced third-party JavaScript, www.foo. The com website will be available directly at www.example. User login information for com website.
To solve this problem, the server can use httpOnly when setting cookies, and cookies with httpOnly will not be readable by JavaScript.
history (not used)
Hisry represents the browser's history
history.back() //Back off history.forward() //Forward
Beginners like to call history when the login page is successfully logged in. Back (), trying to go back to the page before login. This is the wrong way.
In no case should you use history.
8. Operating DOM Objects
core
Browsing a web page is a Dom tree structure
- Update: Update Dom Nodes
- Traversal: Get all Dom nodes,
- Delete: Delete Dom Node
- Add: Add a new Dom node
In the HTML DOM (Document Object Model), each part is a node:
- The document itself is a document node
- All HTML elements are element nodes
- All HTML attributes are attribute nodes
- Text within an HTML element is a text node
- Comments are comment nodes
Get Dom Node
<body> <div id="father"> <h1>Heading One</h1> <p id="p1">p1_id</p> <p class="p2">p2_class</p> </div> <script> //Corresponding css selector var h1=document.getElementsByTagName('h1'); var p1=document.getElementById('p1'); var p2=document.getElementsByClassName('p2'); var father=document.getElementById('father'); var childrens=father.children; //Get all the child nodes under the parent node //father.firstChild //father.lastChild </script> </body>
Update Node
<body> <div id="father"> <h1>Heading One</h1> <p id="p1">p1_id</p> <p class="p2">p2_class</p> <p id="p3">p3_id</p> </div> <script> var p1=document.getElementById('p1'); var p2=document.getElementsByClassName('p2'); var p3=document.getElementById('p3'); var father=document.getElementById('father'); p1.innerText='konan'; //Modify the value of the text as if only the value of the id attribute could be modified p3.innerText='<strong>123</strong>'; //Operating JS p1.style.color='red'; p3.style.fontSize='50px'; p3.style.background='#90ad35'; </script> </body>
Delete Node
- Get the parent node first, then delete yourself through it
<body> <div id="father"> <h1>Heading One</h1> <p id="p1">p1_id</p> <p class="p2">p2_class</p> <p id="p3">p3_id</p> </div> <script> var p1=document.getElementById('p1'); var p2=document.getElementsByClassName('p2'); var p3=document.getElementById('p3'); var father=document.getElementById('father'); father.removeChild(p1); //Delete p1 tag //Delete is a dynamic process, delete the first, the original second becomes the first father.removeChild(father.children[0]); father.removeChild(father.children[1]); father.removeChild(father.children[2]); </script> </body>
Insert Node
<body> <p id="js">1,javascript</p> <div id="list"> <p id="ee">2,javaEE</p> <p id="se">3,javaSE</p> <p id="me">4,javaME</p> <p class="java">5,java</p> </div> <script> var js=document.getElementById('js'); var list=document.getElementById('list'); list.appendChild(js); //Inserting the element'js'to the end of the list will cause the original JS to disappear, which is equivalent to moving //Create a new tag node with js var newP=document.createElement('p'); //Create a p tag 🏷️ newP.id='newp'; newP.innerText='New p Label'; list.appendChild(newP); //Create a script tag var myScript=document.createElement('script'); myScript.setAttribute('type','text/javascript'); //Create a style tag var myStyle=document.createElement('style'); myScript.setAttribute('type','text/css'); myStyle.innerHTML='body{background:green;}'; //Set label content document.getElementsByTagName('head')[0].appendChild(myStyle); //Must be added to the specified location to take effect </script> </body>
insert
<body> <div> <p class="p1" id="p1">This is P1</p> <p class="p2" data-name="p2">This is p2</p> </div> <p id="p3">This is p3</p> <script> let div = document.getElementsByTagName('div')[0]; let p2 = document.getElementsByClassName('p2')[0]; let p1 = document.getElementById('p1'); let insertedNode=div.insertBefore(p2,p1); console.log(returnDom === p2); //true </script> </body>
- p2: the node to be inserted
- p1: the referenced node (that is, before it is inserted)
- insertedNode: Inserted node
- div: parent node
9. Operation Form
What is a form
Working with forms in JavaScript is similar to working with DOM because the form itself is also a DOM tree.
There are several main input controls for HTML forms:
- Text box, corresponding to <input type="text">, for entering text;
- Password box, corresponding to <input type="password">, for entering a password;
- A radio box, corresponding to <input type="radio">, to select an item;
- Check box, corresponding to <input type="checkbox">, to select multiple items;
- Drop-down box, corresponding to <select>, to select an item;
- Hidden text, corresponding to <input type="hidden">, is invisible to the user but will be sent to the server when the form is submitted.
Get Form Value
<body> <form action="#" menth="post "> <p>User name:<input type="text" placeholder="enter one user name" id="user"></p> <p>dense     Code:<input type="password" placeholder="Please input a password" id="psw"></p> <label for="user"></label> <label for="psw"></label> <p> <span>Gender:</span> <input type="radio" name="sex" id="boy"> male <input type="radio" name="sex" id="girl"> female <input type="radio" name="sex" id="ha" value="haha"> Ha </p> </form> <script> let user_id=document.getElementById('user'); let psw_id=document.getElementById('psw'); let boy_id=document.getElementById('boy'); let girl_id=document.getElementById('girl'); //Get the value of the input box user_id.value; psw_id.value; //Get the value of the radio button, the radio box does not have value unless it defaults to value //You can see if true/false is selected ha.value; //You can get the default of ha:'ha' boy_id.checked; girl_id.checked; //Who was selected and who returned true </script> </body>
Submit Form
<head> <meta charset="UTF-8"> <title>Title</title> <!--MD5 Tool class--> <script src="MD5 encryption.js"></script> </head> <body> <form action="#" method="get"> <p>User name:<input type="text" placeholder="enter one user name" id="user"></p> <p>dense     Code:<input type="password" placeholder="Please input a password" id="psw"></p> <!--Binding Events onclick Clicked--> <button type="submit" onclick="konan()">Submit</button> </form> <script> function konan(){ let user_id=document.getElementById('user'); let psw_id=document.getElementById('psw'); //md5 algorithm psw_id.value=MD5(psw_id.value); alert("Submitted successfully!"); } </script> </body>
- Advanced
<head> <meta charset="UTF-8"> <title>Title</title> <!--MD5 Tool class--> <script src="MD5 encryption.js"></script> </head> <body> <!--Form binding events,οnsubmit="function" true,false,In the corresponding function return Return this result to the form, using onsubmit function--> <form action="#" method="get" onsubmit="return konan()"> <p>User name:<input type="text" placeholder="enter one user name" id="user"></p> <p>dense     Code:<input type="password" placeholder="Please input a password" id="psw"></p> <input type="hidden" id="md5-psw" name="psw"> <!--Binding Events onclick Clicked--> <button type="submit">Submit</button> </form> <script> function konan(){ let user_id=document.getElementById('user'); let psw_id=document.getElementById('psw'); let hidden_id=document.getElementById('md5-psw'); //md5 algorithm hidden_id.value=MD5(psw_id.value); alert("Submitted successfully!"); //Form content can be checked, true is passed, false prevents submission return true; } </script> </body>
10. jQuery
Initial knowledge of jQuery
<body> <script src="jQuery3.0.6.js"></script> <a href="#"Id=" test ">click on me </a> <script> //Selector with css $('#test').click(function(){ alert('hello,jQuery!'); }) </script> </body>
selector
<script> //Native js document.getElementsByTagName(); //Label document.getElementById(); //id document.getElementsByClassName(); //class //Selectors in jQuery css are all available $('p').click(); //tag chooser $('#id').click(); // id selector $('.class').click(); //class selector </script>
- Official documents: https://jquery.cuishifeng.cn
Event
<head> <meta charset="UTF-8"> <title>Event</title> <script src="jQuery3.0.6.js"></script> <style> #divMove{ width: 500px; height: 500px; border: 1px solid red; } </style> </head> <body> <!--Gets the coordinates of the current mouse--> mouse:<span id="mouseMove"></span> <div id="divMove"> Move your mouse here to try it <div> <script> //Respond to events when the page is loaded $('#divMove').mousemove(function (e){ $('#mouseMove').text('x:'+e.pageX+'y:'+e.pageY); }) </script> </div> </div> </body>
https://jquery.cuishifeng.cn/mousemove.html
Operating on Dom elements
- Node Text Operation
$('#Test-ul li[name=python]'. Text(); // Get value $('#Test-ul li[name=python]'. Text ('set value'); // Set Value $('#test-ul').html(); $('#test-ul').html('<strong>konan</strong>');
- css operation
$('#test-ul li[name=python]').css({'color':'red'})
- Display and Hide of Elements: Essential display:none
$('#test-ul li[name=python]').show() $('#test-ul li[name=python]').hide()
- test
$(window).width() $(window).height() $('#test-ul li[name=python]').toggle()