[front end] Javascript advanced learning summary

preface

Basic variable syntax, conditional loop statements (similar to c language), etc Rookie tutorial

Javascript function

  1. Write html input stream
<script>
document.write("<h1>This is a title</h1>");
document.write("<p>This is a paragraph.</p>");
</script>
  1. Response event
    If the onclick method is declared in the button button, the corresponding event will be triggered
<button type="button" onclick="alert('welcome!')">Point me!</button>
  1. Change the html content, including html images as well
<p id="demo">
JavaScript Can change HTML The content of the element.
</p>
<script>
function myFunction()
{
	x=document.getElementById("demo");  // Find the content corresponding to the demo element by id
	x.innerHTML="Hello JavaScript!";    // Custom change content
}
</script>
<button type="button" onclick="myFunction()">click here </button>

Customize the changes in the myFunction method:

Change content: x.innerHTML=" "
Change style: x.style.color=" " //color is one of the attributes contained in style
 Judge the content, such as the input content(value Value) is numeric:
var x=document.getElementById("demo").value;
	if(x==""||isNaN(x))
	{
		alert("Not a number");
	}

Javascript usage

statement

Must be placed between < script > and < / script > tags
Variables are declared with var, and the declaration string is:

var firstName = "John"
var firstName = new String("John")

usage

basic operation

<script>
window.alert(5 + 6);//Using windows alerts
document.getElementById("demo").innerHTML = "Paragraph has been modified."; //Modification content
document.write(Date()); //write in
console.log(c); //Write to console, F12 debug window, console menu
</script>
document.write("Hello \
world!");

function

//You can also declare global and local variables
var carName = " Volvo"; //overall situation
function myFunction(var1,var2)
{
 var carName = "Volvo"; //local
 code
}

event

<some-HTML-element some-event="JavaScript code">
For example:
<button onclick="this.innerHTML=Date()">What's the time now?</button>//onclick content can be a declared function

attribute

//Use the constructor property to check whether the object is an Array (including the string "Array"):
function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
// Use the constructor property to check whether the object is a Date (including the string "Date"):
function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date") > -1;
}

The global method Number() converts a string to a number. Number ("3.14") / / 3.14 is returned
The global method String() can convert numbers to strings. String(123) / / convert the number 123 into a string and return

regular expression

grammar

/Regular expression body / modifier (optional)

method

The search() method is used to retrieve the substring specified in the string, or the substring matching the regular expression, and return the starting position of the substring.

var str = "Visit Runoob!"; 
var n = str.search(/Runoob/i);
return Runoob Location 6

The replace() method is used to replace some characters in a string with others, or to replace a substring that matches a regular expression.
The test() method is used to detect whether a string matches a pattern. If the string contains matching text, it returns true; otherwise, it returns false.

var patt = /e/;
patt.test("The best things in life are free!");
//Judge whether the string contains e and return true
//Judge whether the input is composed of numbers, letters and underscores
/^\w+$/.test(str);
//Determines whether the string consists entirely of letters
var isletter = /^[a-zA-Z]+$/.test(val);

The exec() method is used to retrieve a match for a regular expression in a string.
This function returns an array containing matching results. If no match is found, the return value is null.

Regular expression form validation rule:

/*With decimal*/
function    isDecimal(strValue )  {  
   var  objRegExp= /^\d+\.\d+$/;
   return  objRegExp.test(strValue);  
}  

/*Verify whether the Chinese name is composed */
function ischina(str) {
    var reg=/^[\u4E00-\u9FA5]{2,4}$/;   /*Define validation expressions*/
    return reg.test(str);     /*Verify*/
}

/*Check whether it is all composed of 8 digits */
function isStudentNo(str) {
    var reg=/^[0-9]{8}$/;   /*Define validation expressions*/
    return reg.test(str);     /*Verify*/
}

/*Verify phone code format */
function isTelCode(str) {
    var reg= /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
    return reg.test(str);
}

/*Check whether the email address is legal */
function IsEmail(str) {
    var reg=/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
    return reg.test(str);
}

exception handling

The try statement allows us to define a block of code for error testing at execution time.
The catch statement allows us to define the code block to be executed when an error occurs in the try code block.
finally statement executes the code block regardless of whether an exception is generated in the previous try and catch
The JavaScript statements try and catch appear in pairs.

function myFunction() {
  var message, x;
  message = document.getElementById("p01");
  message.innerHTML = "";
  x = document.getElementById("demo").value;
  try { 
    if(x == "") throw "The value is empty";
    if(isNaN(x)) throw "Value is not a number";
    x = Number(x);
    if(x > 10) throw "too big";
    if(x < 5) throw "Too small";
  }
  catch(err) {
    message.innerHTML = "error: " + err + ".";
  }
  finally {
    document.getElementById("demo").value = "";
  }
}

this keyword

In a method, this represents the object to which the method belongs.
If used alone, this represents a global object.
In the function, this represents the global object.
In the function, in strict mode, this is undefined.
In an event, this represents the element that receives the event.
Methods like call() and apply() can reference this to any object.

var person = {
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

let keyword

The variables declared by let are only valid in the code block where the let command is located, and the scope is smaller than that of var

var i = 5;
for (var i = 0; i < 10; i++) {
    // Some code
}
// Here the output i is 10

let i = 5;
for (let i = 0; i < 10; i++) {
    // Some code
}
// Here the output i is 5

In the first example, the var keyword is used, and the declared variables are global, including in circulation and out of circulation.

In the second example, the let keyword is used. The scope of the declared variables is only in the circulatory system, and the variables outside the circulatory system are not affected.

Javascript asynchronous programming

Synchronous execution is in the order of your code, asynchronous execution is not in the order of your code, and asynchronous execution is more efficient.

Callback function

//The program waits three seconds before executing
function print() {
    document.getElementById("demo").innerHTML="RUNOOB!";
}
setTimeout(print, 3000);

setTimeout in this program is a process that takes a long time (3 seconds). Its first parameter is a callback function and the second parameter is the number of milliseconds. After the function is executed, a sub thread will be generated. The sub thread will wait for 3 seconds, then execute the callback function "print" and output "Time out" on the command line.

Asynchronous AJAX

XMLHttpRequest is often used to request XML or JSON data from a remote server. A standard XMLHttpRequest object often contains multiple callbacks:

var xhr = new XMLHttpRequest();
 
xhr.onload = function () {
    // Output received text data
    document.getElementById("demo").innerHTML=xhr.responseText;
}
 
xhr.onerror = function () {
    document.getElementById("demo").innerHTML="Request error";
}
 
// Send asynchronous GET request
xhr.open("GET", "https://www.runoob.com/try/ajax/ajax_info.txt", true);
xhr.send();

Use with jquery

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rookie tutorial(runoob.com)</title>
<script src="https://Cdn.staticfile.org/jquery/1.10.2/jquery.min.js "> / / introduce jquery
</script>
<script>

$(document).ready(function(){
	$("button").click(function(){
		$.get("/try/ajax/demo_test.php",function(data,status){
			alert("data: " + data + "\n state: " + status);
		});
	});
});
</script>
</head>
<body>

<button>Send a HTTP GET Request and get the returned results</button>

</body>
</html>

PS: js ready function
The function executed after the DOM is completed and the page is fully displayed.

Call mode:

1. $(document).ready(function(){ })

2. $().ready(function(){ })

3. $(function() {})

Keywords: Javascript html regex

Added by vigour on Sun, 03 Oct 2021 04:38:32 +0300