Novice JavaScript Basic Collation 1_ Basics

Source: Internet
Author: User

1

Copy Code code as follows:

Write HTML content in page
document.write ("

2
Copy Code code as follows:

To prevent browsers that do not support JavaScript to display JS as the content of the page
The two forward slashes at the end of the comment line are JavaScript annotation symbols that prevent the JavaScript compiler from compiling the line.
<script type= "Text/javascript" >
<!--
document.write ("Hello world!");
-->
</script>

3
Copy Code code as follows:

Various ways of the OnLoad event
The first way to add the onload event through the body tag
<script type= "Text/javascript" >
Function message () {alert ("This balloon is invoked through the OnLoad event.) ");}
</script>
<body onload= "message ()" >
The second way to invoke the OnLoad event directly with the window function
<script type= "Text/javascript" language= "JavaScript" >
Window.onload=message;
Function message () {alert ("This balloon is invoked through the OnLoad event.) "); }
</script>

4
Where JavaScript is placed
When the page is loaded, JavaScript is executed in the body section. (Direct execution)
When invoked, the JavaScript in the Head section is executed.
Head section
The script that contains the function is located in the Head section of the document. So we can make sure that the script is loaded before the function is invoked.

5.
The role of semicolons
Semicolons are optional (according to JAVASCRIPT standards), the browser ends the line as the end of the statement, and by using semicolons, you can write multiple statements on one line.

6.
Rules for JavaScript variable names:
Variable is case sensitive (Y and Y are two different variables)
Variable must start with a letter or underscore

7.
Declaration of variables
If the variable you are assigning has not been declared, the variable is declared automatically.
Cases:
x=5; Carname= "Volvo";
The same effect as the following statements: Var x=5; var carname= "Volvo";

8.
Comparison operators
Operator Description Example
= = = Congruent (value and type) x===5 to true; x=== "5" to False

9.
Conditional operator (triple-Mesh operator)
JavaScript also contains conditional operators that assign values to variables based on certain criteria.
Name= ("Liuhuan" = "LH")? " Liu Huan ":" "Singer";


10.
Get current system time (hours)
var d = new Date ()
var time = d.gethours ()

11.
Random number
var num=math.random ();
The resulting pseudo-random number is between 0 and 1 (including 0, excluding 1), that is, the return value may be 0, but always less than 1. Random number on first load of JScript

The generator is generated automatically.

12.
Get today's number of weeks (Sunday is 0, week 1-6 is 1-6)
var d = new Date ()
Theday=d.getday ()

13.
Trigger event for a button
<input type= "button" onclick= "Disp_alert ()" Value= "Show Warning Box"/>

14.
Popup Content Wrapping Line
Alert ("Say hello to you again!") Here, we show you how "+ ' \ n ' +" adds a line to the warning box. ")

15.
Confirmation Box (Delete method)
Confirm ("text")
<script type= "Text/javascript" >
function Show_confirm ()
{
var r=confirm ("Confirm deletion?");
if (r==true) {
Alert ("Delete succeeded!");
}
else{
Alert ("Delete failed!");
}
}
</script>

16.
Pop-up box for user interaction (can enter text balloon)
Prompt ("text", "Default value")
<script type= "Text/javascript" >
function Disp_prompt ()
{
var name=prompt ("Please enter your name", "Bill Gates")
if (name!=null && name!= "") {
document.write ("Hello!") "+ name +" How was your day? ")
}
}
</script>

17.
Functions with parameters and return a value
<script type= "Text/javascript" >
function Product (A,B)
{
return a*b;
}
</script>
<body>
<script type= "Text/javascript" >
document.write (Product (6,5))
</script>
</body>

18.
For loop (in this case, dynamically generating H tags in html)
<body>
<script type= "Text/javascript" >
for (i = 1; I <= 6; i++) {
document.write ("document.write ("}
</script>
</body>

19.
Break Jump Statement
<script type= "Text/javascript" >
var i=0
for (i=0;i<=10;i++) {
if (i==3) {break}
document.write ("number is" + i)
document.write ("<br/>")
}
</script>
<p> Explanation: Loops are interrupted at i=3. </p>


20.
Continue jump out of statements
<script type= "Text/javascript" >
var i=0
for (i=0;i<=10;i++) {
if (i==3) {continue}
document.write ("number is" + i)
document.write ("<br/>")
}
</script>
<p> Explanation: When i=3, the loop is interrupted and the loop is resumed from the next value. </p>
Value is: 01245678910

21st.
For In loop (equivalent to a foreach loop in. net)
<body>
<script type= "Text/javascript" >
var x
var mycars = new Array ()
Mycars[0] = "BMW"
MYCARS[1] = "Mercedes"
MYCARS[2] = "Bentley"

for (x in Mycars)
{
document.write ("x is the value of" +x+ "<br/>");
document.write (Mycars[x] + "<br/>")
}
</script>
</body>


22.
JavaScript events
OnLoad a page or image is finished loading//page loading
OnUnload User Exit Page

onfocus Element gets focus
onblur element lost focus/form validation
onchange users to change the contents of a domain
OnReset reset button is clicked
The onsubmit submit button is clicked//used to validate all form fields before submitting the form.
For example:
(The Checkform () function is invoked when the user clicks the confirmation button in the form.) The return value of the Checkform () function is type bool, and if the return value is true, the

Submit the form, otherwise cancel the submission. )
<form method= "POST" action= "xxx.htm" onsubmit= "return Checkform ()" >

OnKeyDown a key to a keyboard is pressed
onkeypress The key of a keyboard is pressed or hold//keyboard operation
OnKeyUp a key to a keyboard is released

OnClick mouse clicks on an object
OnDblClick mouse to double-click an object
OnMouseDown a mouse button is pressed//mouse action
OnMouseMove Mouse is moved
onMouseOut the mouse away from an element
onMouseOver Mouse is moved over an element
OnMouseUp a mouse button is released

Onabort image loading is interrupted
OnError An error occurred while loading a document or image

OnResize window or frame is resized
Onselect Text is selected

23.
Error prompt Err.Description in JS and its Try...catch statement
For example:
<script type= "Text/javascript" >
var txt= ""
Function message () {
try{
Adddlert ("Welcome guest!")
}
catch (Err) {
Txt= "There is an error in this page. \ n '
txt+= "Error Description:" + Err.Description + "\ n"
txt+= "Click OK" to continue. \ n '
alert (TXT);
}
}
</script>

24.
//Try...catch statement with confirmation box
<script type= "Text/javascript"
var txt= ""
function Message () {
 try{
    adddlert ("Welcome guest!")
   } There are errors in the
 catch (err) {
   txt= page. \ n "
   txt+=" click "OK" to continue viewing this page, \ n "
   txt+=" click "Cancel" to return to the home page. \ n "
   if (!confirm (TXT))
   {
   document.location.href=" ... /index.html "
  }
   }
}
</script>
<body>
 <input type= "button" value= "View Messages" onclick= "message ()"/>
</body>


25.
Create exception (exception or error). (Used with try...catch statements)
For example:
<script type= "Text/javascript" >
var x=prompt ("Please enter a number between 0 and 10:", "")
try{
if (x>10)
Throw "ERR1"
else if (x<0)
Throw "ERR2"
else if (isNaN (x))
Throw "Err3"
}
catch (er) {
if (er== "ERR1")
Alert ("Wrong!") The value is too large! ")
if (er = = "ERR2")
Alert ("Wrong!") The value is too small! ")
if (er = = "ERR3")
Alert ("Wrong!") The value is not a number! ")
}
</script>


26.
Use of return true and return True
(It can return a bool parameter and continue to be judged)
function Jiance (msg,url,l) {
Alert ("Are you sure?")
return True
}
function Jieguo () {
if (Jiance ()) {
Alert ("Yes");
}
else{
Alert ("No");
}
}

27.
OnError Events
<script type= "Text/javascript" >
Trigger OnError Event when an error occurs
Onerror=handleerr;
var txt= ""
function Handleerr (msg,url,l) {
Txt= "There is an error in this page. \ n '
txt+= "Error:" + msg + "\ n"
txt+= "url:" + URL + "\ n"
txt+= "line:" + L + "\ n"
txt+= "Click OK" to continue. \ n '
Alert (TXT)
return True
}
Function message () {
Adddlert ("OK?")
}
</script>
<input type= "button" value= "View Messages" onclick= "message ()"/>
</body>


28.
Use backslashes in JavaScript to add special characters to a text string.
For example:
var txt= "We are the so-called \ Vikings\" from the north. "
document.write (TXT)

29.
JavaScript considerations
1. JavaScript is case sensitive
2. JavaScript ignores extra spaces
3. You can use a backslash for line wrapping when writing code
Cases:
document.write ("Hello \

World! ");

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.