W3school Learning-Getting started with JavaScript

Source: Internet
Author: User
Tags html form tag name jquery library

When you look at the client code, you often encounter JavaScript scripts, the system to learn a bit more in the future to understand the client is good.

1. Application Scenarios

Improved design

Validating forms

detecting browsers

Create cookies, etc.


2. Getting started instance the document here is the HTML DOM object in JS
Http://www.w3school.com.cn/jsref/dom_obj_document.asp
1. Change HTML content
document.write ("

2. Change the HTML style
X=document.getelementbyid ("demo")  //Find element x.style.color= "#ff0000";           //Change style

3. Verify the input
If IsNaN (x) {alert ("Not Numeric")};


3. Syntax 1. Label

The lines of code between <script> and </script> contain JavaScript


2. Functions and Events

In general, functions are closely related to events.

We need to execute code when an event occurs, such as when the user taps the button.

If we put JavaScript code in a function, we can call it when the event occurs.


3. js file Independence and introduction

It is common practice to put functions in the

The file name extension for external JavaScript files is. js.

<! DOCTYPE html>

4. JS output document.write () to the document output write content.
If document.write is executed after the document has finished loading, the entire HTML page will be overwritten
5. variable var declaration, commonly used when the number and string dynamic type, the same variable, that can be a number, or it can be a string
6. JS object: JSON
7. JS Array
8. Create a JS object
Person=new Object ();p erson.firstname= "Bill";p erson.lastname= "Gates";p erson.age=56;person.eyecolor= "Blue";

9. Functions
function MyFunction ( var1 , var2 ) {Here is the code to execute}
10. Operator, If-else, switch, for, when, break, continue syntax, similar to C language
One. Try ... throw ... catch ... Syntax instances
<script>function myFunction () {try {var X=document.getelementbyid ("Demo"). Value; if (x== "")throw "empty"; if (IsNaN (x))throw "not a number"; if (x>10)throw "too high"; if (x<5)throw "too low";  }catch (Err) {var Y=document.getelementbyid ("mess"); Y.innerhtml= "Error:" + Err + ".";}} </script>


4. JavaScript Form Validation
JavaScript can be used to validate these input data in an HTML form before the data is sent to the server.

These typical forms of data that are validated by JavaScript are:
1. Has the user filled in the required fields in the form?
2. Is the email address entered by the user legal?
3. Has the user entered a valid date?
4. Does the user enter text in the Data field (numeric field)?

Such as:
function validate_required (field,alerttxt) {with (field) {if (value==null| | value== "")  {alert (alerttxt); return False}else {return True}}}

Http://www.w3school.com.cn/js/js_form_validation.asp

5. How does JS manipulate HTML DOM elements? The DOM structure of HTML
1. Find HTML elements by ID
var X=document.getelementbyid ("Intro");

3. Find HTML elements by tag name
var X=document.getelementbyid ("main"); var y=x.getelementsbytagname ("P");

3. If you want to change the content of HTML elements, syntax:

document.getElementById (ID). innerhtml=New HTML


6. JS DOM Event 1. When the user clicks the mouse
onclick="this.innerHTML=‘谢谢!‘"> Click on the Text 
The button is the same.
2. OnLoad and OnUnload events when a webpage is loaded
The onload and OnUnload events are triggered when the user enters or leaves the page.
The OnLoad event can be used to detect the browser type and browser version of the visitor and to load the correct version of the Web page based on that information.
The onload and OnUnload events can be used to process cookies.
<body onload= "checkcookies ()" >

3. When the image is loaded

4. onmouseover and onmouseout event <div onmouseover= "MOver (This)" onmouseout= "Mout" when the mouse is moved to the element (this) "style=" Background-color:green;width:120px;height:20px;padding:40px;color: #ffffff; " > Move the mouse over the top </div>


5. When the input field is changed
onchange Events

<input type= "text" id= "fname" onchange= "uppercase ()" >

6. The onclick event when an HTML form is submitted
7. When the user triggers the button

OnMouseDown, onmouseup, and onclick events

<div onmousedown= "MDown (This)" onmouseup= "mUp (This)" style= "Background-color:green;color: #ffffff; width:90px; height:20px;padding:40px;font-size:12px; " > Click here </div>

9. DOM node operation additions and deletions
Increase
var para=document.createelement ("P");
var Node=document.createtextnode ("This is the new paragraph. ");
Para.appendchild (node);

Check:
var Element=document.getelementbyid ("Div1");

By deleting:
Parent.removechild (child);

7. JS Object JavaScript provides multiple built-in objects, such as String, Date, Array, and so on.
Objects are just special data types with properties and methods.

Some features of JS built-in objects:
1. JS Digital Digital properties and methods
Property:
MAX VALUE
MIN VALUE
Negative infinitive
POSITIVE Infinitive
NaN
Prototype

Constructor


Method:
Toexponential ()
ToFixed ()
Toprecision ()
ToString ()
ValueOf ()
2. js string attribute length Txt.length style small (), big (), bold (), italics () blink (), fixed (), FontColor ("ddd"), FontSize (+) t Ouppercase (), toLowerCase () sub (), SUP () Link ("Http://lll ...")
Find sub-string location: Str.indexof ("Hello")

Match specific characters: Str.match ("World")

String substitution: Str.replace (/microsoft/, "W3school")

3. js date () return format:Thu Feb 17:55:22 gmt+0800 (CST)

GetTime ()
GetTime () returns the number of milliseconds since January 1, 1970.
setFullYear ()
How to use setFullYear () to set a specific date.
toUTCString ()
How to use toUTCString () to convert the date of the day (based on UTC) to a string.
GetDay () returns day of the week, number 0-7, starting from Sunday
4. JS Array
var mycars=new Array("Saab","Volvo","BMW")
For ... In declaration
Use the for...in declaration to loop through the elements in the output array.
Merging two arrays-concat ()
How to use the Concat () method to merge two arrays.
Make a string of elements of an array-join ()
How to use the Join () method to compose all elements of an array into a string.
Text array-sort ()
How to use the sort () method to literally sort the array.
Array of numbers-sort ()

How to use the sort () method to sort the arrays numerically.


5. Math Object

Round () rounding

Max (), Min ()

Random () returns a number between 0-1

Floor (), ceil ()

Constant:

Math.e
Math.PI
Math.sqrt2
Math.sqrt1_2
Math.ln2
Math.ln10
math.log2e
math.log10e

6. JS Regular expression

Test

Retrieves the specified value in a string. The return value is true or false.


Exec:

The return value is the value that was found. If no match is found, NULL is returned.


Compile

Used to change the value of a regular expression

var patt1=new RegExp ("E");d Ocument.write (Patt1.test ("The Best things on life is Free");p att1.compile ("D"); document.write (Patt1.test ("The best things in life is free");

8. JS BOM Model Browser The object model

1. Window height, Width, Document object, indicating browser window properties

Method:

Open (), close (), MoveTo (), Resizeto ()

2. Screen

Screen.availwidth-Available screen widths

Screen.availheight-The available screen height


3. Location

The Location.href property returns the URL of the current page.

The Location.pathname property returns the path name of the URL.

The Location.assign () method loads the new document.


4. History

History.back ()-Same as clicking Back button in browser
History.forward ()-Same as clicking the button in the browser forward


5. Navigator

Contains browser information

such as appCodeName, AppName, AppVersion, cookieenabled, platform, useragent, systemlanguage, etc.


6. Message box

Alert () Warning box

Confirm () Confirm, Cancel box

Prompt () prompt box


7. Chronograph function, MS Unit

SetTimeout ()
Future execution of code at some time
Cleartimeout ()
Cancel settimeout ()


8. Cookies

Document.cookie

Create, store, retrieve, and check cookies

Example Http://www.w3school.com.cn/tiy/t.asp?f=jseg_cookie_username


9. jquery Library

jquery is a famous library of JS

Reference JQuery
<script src= "Https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" >
</script>

The underlying syntax is: $ (selector). Action ()
Dollar sign definition JQuery
Selector (selector) "Query" and "find" HTML elements
JQuery Action () performs an operation on an element


Ten. AJAX

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).


AJAX is the art of exchanging data with a server and updating parts of a Web page without reloading the entire page.

AJAX is a technique for creating fast, Dynamic Web pages.


XMLHttpRequest is the basis of AJAX.

XMLHttpRequest is used to exchange data with the server in the background. This means that you can update a part of a webpage without reloading the entire page.

Variable=new XMLHttpRequest ();

The XMLHttpRequest object is used to exchange data with the server.

To send the request to the server, we use the open () and send () methods of the XMLHttpRequest object

1. Get request

Xmlhttp.open ("GET", "demo_get.asp", true); Xmlhttp.send ();

2. Post request

Xmlhttp.open ("POST", "ajax_test.asp", true); Xmlhttp.setrequestheader ("Content-type", "application/ X-www-form-urlencoded "); Xmlhttp.send (" fname=bill&lname=gates ");


The async parameter of the open () method must be set to True if the XMLHttpRequest object is to be used with AJAX:
Xmlhttp.open ("GET", "ajax_test.asp", true);

3. Response

To obtain a response from the server, use the ResponseText or Responsexml property of the XMLHttpRequest object.

The ResponseText property returns a response in the form of a string:

document.getElementById ("Mydiv"). Innerhtml=xmlhttp.responsetext;

If the response from the server is XML and needs to be parsed as an XML object, use the Responsexml property

4. XHR Events

Description of the onReadyStateChange

Http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_onreadystatechange.asp

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

  • 0: request uninitialized
  • 1: Server connection established
  • 2: Request received
  • 3: 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:

Xmlhttp.onreadystatechange=function ()  {  if (xmlhttp.readystate==4 && xmlhttp.status==200)    {    document.getElementById ("mydiv"). Innerhtml=xmlhttp.responsetext;    }  }

W3school Learning-Getting started with JavaScript

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.