First entry JavaScript knowledge point (vi)

Source: Internet
Author: User
Tags modifier unsupported

Regular expressions

REGEXP is the abbreviation for regular expressions.

Define REGEXP

The RegExp object is used to store the retrieval mode.

Define the RegExp object with the New keyword. The following code defines the RegExp object named Patt1, whose pattern is "e":

var patt1=new RegExp("e");

When you use the RegExp object to retrieve in a string, the character "e" is searched.

There are 3 methods of REGEXP objects:

Test ()

    • The test () method retrieves the specified value in the string. The return value is true or false.

EXEC ()

    • The EXEC () method retrieves the specified value in the string. The return value is the value that was found. If no match is found, NULL is returned.

Compile ()

    • The compile () method is used to change the REGEXP. Compile () can either change the retrieval mode or add or remove the second parameter.
Modifier
modifier Description
I Performs a match that is not case sensitive.
G Performs a global match (finds all matches rather than stops after the first match is found).
M Performs multi-line matching.

Square brackets

Square brackets are used to find characters in a range:

An expression Description
[ABC] Look for any characters between square brackets.
[^ABC] Look for any characters that are not in square brackets.
[0-9] Look for any number from 0 to 9.
[A-z] Finds any characters from a to lowercase z from a small write.
[A-z] Look for any characters from uppercase A to uppercase Z.
[A-z] Look for any characters from uppercase A to lowercase z.
[ADGK] Finds any character within a given collection.
[^ADGK] Finds any character outside the given collection.
(Red|blue|green) Finds any of the specified options.
Metacharacters

Metacharacters (metacharacter) is a character that has a special meaning:

Meta character Description
. Finds a single character, in addition to line breaks and line terminators.
\w Find the word character.
\w Finds non-word characters.
\d Find numbers.
\d Finds non-numeric characters.
\s Find white space characters.
\s Finds non-whitespace characters.
\b Matches the word boundary.
\b Matches a non-word boundary.
/ Find NUL characters.
\ n Find line breaks.
\f Find a page break.
\ r Look for the carriage return character.
\ t Find tabs.
\v Find vertical tabs.
\xxx Find the characters that are specified in octal number XXX.
\xdd Finds the characters specified in hexadecimal number DD.
\uxxxx Finds the Unicode characters specified in hexadecimal number xxxx.
Quantifiers
quantifier Description
n+ Matches any string that contains at least one n.
N Matches any string that contains 0 or more N.
N? Matches any string that contains 0 or one n.
N{X} Matches a string that contains a sequence of X N.
N{x,y} Matches a string containing a sequence of X or Y N.
N{x,} Matches a string that contains at least X N of a sequence.
n$ Matches any string that ends with N.
^n Matches any string that begins with N.
? =n Matches any string immediately followed by the specified string n.
?! N Matches any string that does not follow the specified string n immediately thereafter.
RegExp Object Properties
Properties Description FF IE
Global RegExp whether the object has a flag g. 1 4
IgnoreCase RegExp whether the object has a flag I. 1 4
LastIndex An integer that indicates the character position at which to start the next match. 1 4
Multiline RegExp whether the object has a flag m. 1 4
Source The source text of the regular expression. 1 4
RegExp Object Methods
Method Description FF IE
Compile Compiles the regular expression. 1 4
Exec Retrieves the value specified in the string. Returns the found value and determines its location. 1 4
Test Retrieves the value specified in the string. Returns TRUE or FALSE. 1 4
Methods for String objects that support regular expressions
Method Description FF IE
Search Retrieves a value that matches a regular expression. 1 4
Match Finds a match for one or more regular expressions. 1 4
Replace Replace the substring that matches the regular expression. 1 4
Split Splits a string into an array of strings. 1 4
HTML5 new features: Canvas what is canvas

<canvas>is a new element of HTML5, you can use JavaScript scripts to draw graphics.

<canvasis a rectangular area in which you can control each pixel.

Introducing Canvas
<canvas id="canvas" width="300" height="300"></canvas>
Width and Height properties

When the width and height are not set, the canvas width is initialized to 300 pixels and the height is 150 pixels. The element can use CSS to define the size, but the image will stretch to fit its frame size when it is drawn: if the size of the CSS is not the same as the original canvas, it will appear distorted.

*注意*: 如果你绘制出来的图像是扭曲的, 尝试在<canvas>的属性中明确规定宽和高,而不是使用CSS。
Compatibility

Some older browsers (especially IE9 IE browsers) or text browsers do not support HTML element "canvas", which <canvas> displays the contents of the tags inside them, so we can <canvas> provide some alternative content on these unsupported browsers, and support <canvas>Browser will ignore the content contained in the container and just render the canvas normally.

<canvas id="myCanvas" width="150" height="150">  如果您的浏览器不支持Canvas,那么您将看到本行文字</canvas>
Labels are not saved

Unlike elements, an <canvas> element requires an end tag ( </canvas> ). If the end tag does not exist, the remainder of the document is considered an alternative and will not be displayed.

Get drawing context (the rendering contexts)

The canvas was initially blank. If you want to do something with canvas, you need to get the canvas's drawing context object. The <canvas> element has a way of doing it getContext() , which is used to get the rendering context and its painting function. getContext()only one parameter, the format of the context. For 2D images, this format parameter is "2d" .

var canvas = document.getElementById(‘canvas‘);var ctx = canvas.getContext(‘2d‘);

If you <canvas> run the above code in an unsupported browser, an error is thrown. So before we get the drawing context object, we should check the browser's support for that feature.

var canvas = document.getElementById(‘tutorial‘);if (canvas.getContext){  var ctx = canvas.getContext(‘2d‘);  // drawing code here} else {  // canvas-unsupported code here}
Basic drawing operations

As with the paint program that comes with the Windows operating system, Canvas the two basic drawing operations are fills and strokes. Fills the shape with the specified style (color, gradient, or image), and strokes the line only at the edges of the graphic. The style of padding and strokes depends on two properties, respectively: fillStyle and strokeStyle . The values of these two properties can be strings, gradient objects, or schema objects, and their default values are "#000000" . If you assign them a string value that represents a color, you can use any format that specifies the color value in the CSS, including the color name, hexadecimal code, RGB, RGBA, HSL, or Hsla.

Draw a rectangle

A rectangle is the only shape that can be drawn directly in a 2D context. Methods related to rectangles include fillRect() , strokeRect() and clearRect() . All three methods can receive 4 parameters: The x-coordinate of the rectangle, the y-coordinate of the rectangle, the width of the rectangle, and the height of the rectangle. The units of these parameters are pixels.

Fill Rectangle

fillRect(x, y, width, height)

Draw a rectangle stroke

strokeRect(x, y, width, height)

Clear Rectangle
该方法的功能类似于Windows系统中画图程序的橡皮擦,会将指定矩形矩形区域中的所有内容全部清除。

clearRect(x, y, width, height)

Draw Path

If you want to draw a shape other than a rectangle, you need to customize the drawing path. The drawing context supports many ways to draw paths on the canvas. To draw a path, you must first call the Beginpath () method, which indicates that you want to start drawing a new path. Then, you can actually draw the path by calling the following methods.

arc(x, y, radius, startAngle, endAngle, counterclockwise)

To (x,y) draw an arc for the center of the circle, the radius of radius the arc, the starting and ending angles (in radians), respectively, startAngle and endAngle . The last parameter represents startAngle and endAngle is calculated in a counterclockwise direction, and the value is calculated in a false clockwise direction.

arcTo(x1, y1, x2, y2, radius)

Draws an arc from the previous point, so (x2,y2) far, and passes through with a given radius radius (x1,y1) .

bezierCurveTo(c1x, c1y, c2x, c2y, x, y)

Draws a three-cubic Bezier curve from the previous point, up to (x,y) (c1x,c1y) and (c2x,c2y) as a control point.

lineTo(x, y)

Draw a line from the previous point, so (x,y) far.

moveTo(x, y)

Moves the drawing cursor to (x,y) , without drawing a line.

quadraticCurveTo(cx, cy, x, y)

Draw a two-time Bezier curve from the previous point, so (x,y) far, and as a (cx,cy) control point.

rect(x, y, width, height)

Draws a rectangle from the point, with the (x,y) width and height width specified by and respectively height . This method draws a rectangular path, rather than a strokeRect() fillRect() separate shape that is drawn.

After you have created the path, there are several possible options to follow. If you want to draw a line that connects to the beginning of the path, you can call it closePath() . If the path is complete and you want to fillStyle populate it, you can call the fill() method. Alternatively, you can call the stroke() method to stroke the path, using the strokeStyle . Finally, you can call clip() this method to create a clipping region on the path.

Detection registration page
(function () {var form = document.getElementById (' form ');  var usernameinput = document.getElementById (' username ');  var pwdinput = document.getElementById (' pwd ');  var confirmpwdinput = document.getElementById (' confirmpwd ');  var birthinput = document.getElementById (' birth ');  var usernameinfo = document.getElementById (' Usernameinfo ');  var pwdinfo = document.getElementById (' Pwdinfo ');  var confirmpwdinfo = document.getElementById (' Confirmpwdinfo ');  var birthinfo = document.getElementById (' Birthinfo ');    Detect user Name function Checkusername () {var username = Usernameinput.value;      if (Username.length < 4) {usernameinfo.innerhtml = ' username length cannot be less than 4 bits ';    return false;      } else {usernameinfo.innerhtml = ';    return true;    }}//Detect password function checkpwd () {var pwd = Pwdinput.value;      if (Pwd.length < 6) {pwdinfo.innerhtml = ' password cannot be less than 6 bits in length ';    return false;      } else {pwdinfo.innerhtml = ';    return true; }}//Check car Confirm password function checkconfIrmpwd () {var pwd = Pwdinput.value;    var confirmpwd = Confirmpwdinput.value;      if (pwd!== confirmpwd) {confirmpwdinfo.innerhtml = ' two times the password of the input is inconsistent ';    return false;      } else {confirmpwdinfo.innerhtml = ';    return true;    }}//Detect Birth date function Checkbirth () {var birth = Birthinput.value;    var reg =/^ (19|20) \d\d-\d\d-\d\d$/g;      if (!reg.test (birth)) {birthinfo.innerhtml = ' format is incorrect ';    return false;      } else {birthinfo.innerhtml = ';    return true;  }} usernameinput.addeventlistener (' Blur ', Checkusername, false);  Pwdinput.addeventlistener (' Blur ', checkpwd, false);  Confirmpwdinput.addeventlistener (' Blur ', checkconfirmpwd, false);  Birthinput.addeventlistener (' Blur ', Checkbirth, false); Form.addeventlistener (' Submit ', function (event) {if (! ( Checkusername () && checkpwd () && checkconfirmpwd () && Checkbirth ())) {Event.preventdefault ()    ; }, False);}) ();
Ajaxajax = Asynchronous JavaScript and XML (asynchronous JavaScript and XML). AJAX is a technique for creating fast, Dynamic Web pages. AJAX enables Web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that you can update a part of a webpage without reloading the entire page.

Currently learning Asynchronous statements: SetTimeout (); SetInterval (); AJAX

Creating Ajax
var xhr = new XMLHttpRequest();

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:

var xhr = =new ActiveXObject("Microsoft.XMLHTTP");

therefore: //To determine whether to support Var xhr; if (window. XMLHttpRequest) {xhr = new XMLHttpRequest ();} else {xhr = =new ActiveXObject ("Microsoft.XMLHTTP");} ;

//配置ajax的参数xhr.open(‘GET‘请求方式,‘./test.html‘请求地址,true异步false同步);//发送请求xhr.send();
Method Description
Open (method,url,async)

Specifies the type of request, the URL, and whether the request is processed asynchronously.

  • method: type of request; GET or POST
  • URL: The location of the file on the server
  • Async: True (asynchronous) or false (synchronous)
Send (string)

Sends the request to the server.

  • string: only for POST requests
onReadyStateChange Events

When a request is sent to the server, we need to perform some response-based tasks.

The onreadystatechange event is triggered whenever the readyState changes.

The ReadyState attribute holds state information for XMLHttpRequest.

The following are three important properties of the XMLHttpRequest object:

Properties Description
onReadyStateChange The function (or function name) is called whenever the ReadyState property is changed.
ReadyState

The state of being xmlhttprequest. Vary from 0 to 4.

  • 0: Request not initialized
  • 1: Server Connection established
  • 2: Request received
  • 3: In Request processing
  • 4: The request is complete and the response is ready
Status

$: "OK"

404: Page Not Found

In the onReadyStateChange event, we specify the tasks that are performed when the server responds to readiness to be processed.

When ReadyState equals 4 and the status is 200, the response is ready. Now we're going to accept the response:

//接受响应的时机与步骤xhr.onreadystatechange = function(){    if(xhr.readyState === 4 && xhr.status==200){        console.log(xhr.responseText);    }}
Passing data to the server Localstorage local storage

HTML5 new feature, low version does not support

Localstorage is the data directly in the computer's hard drive, and will not be deleted by restarting the browser or comments. However, only data of a string type can be stored.

Counter

-0+

JS Code

(function(){    var subBtn = document.getElementById(‘sub‘);    var numSpan = document.getElementById(‘num‘);    var addBtn = document.getElementById(‘add‘);    var num = 0;//每次刷新页面后span的初始值都是0    addBtn.addEventListener(‘click‘,function(){        num++;        numSpan.innerHTML = num;    },false);    subBtn.addEventListener(‘click‘,function(){        num--;        numSpan.innerHTML = num;    },false);})();

To make the initial value of the span the last value for each time the page is refreshed, use Localstorage

(function(){    var subBtn = document.getElementById(‘sub‘);    var numSpan = document.getElementById(‘num‘);    var addBtn = document.getElementById(‘add‘);    //使用localStorage可以让每次刷新后,初始值都是上次最后的值    //先判断localStorage有没有值,如果没有就赋值初始值0    if(localStorage.num === undefined){        localStorage.num = 0;    }    //根据localStorage的值赋值页面加载时span的初始值    numSpan.innerHTML = localStorage.num;    addBtn.addEventListener(‘click‘,function(){        num++;        numSpan.innerHTML = num;    },false);    subBtn.addEventListener(‘click‘,function(){        num--;        numSpan.innerHTML = num;    },false);})();
Convert the JSON file to the array literal eval function to run a string according to the JS code (you can execute the retrieved JSON text according to the JS code)
var listOfStudents = eval(xhr.responseText);
    • However, his safety performance is relatively low. Easy to prepare hacker attacks.
Json.parse
var listOfStudents = JSON.parse(xhr.responseText);
Add: Convert an array to JSON text
var str = JSON.stringfy(listOfStudents);

Tips

The parent of the TR in table is Tbody, which is omitted when it is usually written, and the browser automatically helps us to write

First entry JavaScript knowledge point (vi)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.