JS Common built-in objects, Dom objects, BOM objects

Source: Internet
Author: User
Tags array sort modifiers setcookie javascript array

11, HTML element event attributes, such as onclick= "", double quotation marks can be a method bar, can be JS code (no add <script> tags)

12. JavaScript built-in objects, properties, and methods (you should also avoid using JavaScript built-in objects, properties, and method names as JavaScript variables or function names):
Array Date eval function hasownproperty
Infinity isfinite IsNaN isprototypeof length
Math NaN Name Number Object
Prototype String toString undefined valueOf


13. Windows Reserved Keywords: (in HTML, you must do the same for portability) avoid using the names of HTML and Windows objects and properties as Javascript variables and function names:)
Alert all anchor Anchors area
Assign Blur button checkbox clearinterval
Cleartimeout clientinformation Close closed confirm
Constructor Crypto decodeURI decodeURIComponent defaultstatus
Document element Elements embed embeds
encodeURI encodeURIComponent Escape Event FileUpload
Focus form Forms Frame Innerheight
Innerwidth Layer Layers Link Location
Mimetypes Navigate Navigator Frames framerate
Hidden history image Images offscreenbuffering
Open opener Option Outerheight Outerwidth
Packages Pagexoffset pageYOffset Parent parsefloat
parseint Password Pkcs11 plugin prompt
Propertyisenum Radio Reset ScreenX ScreenY
Scroll secure Select self setinterval
SetTimeout Status Submit Taint text
TextArea Top unescape untaint window

14. HTML Event handle (in addition, you should avoid using the name of the HTML event handle as the variable and function name of the Javascript.) ):
onblur onclick onerror onfocus
onkeydown onkeypress onkeyup onmouseover
OnLoad onmouseup onmousedown onsubmit

15. Custom Objects:
With JavaScript, you can define and create your own objects.
There are two different ways to create a new object:
Defining and creating an instance of an object
Use a function to define an object, and then create a new object instance
1), create objects, and assign values
Person=new Object ();
Person.firstname= "John";
Person.lastname= "Doe";
person.age=50;
Person.eyecolor= "Blue";
Equivalent: var person={firstname: "John", LastName: "Doe", Age:50,eyecolor: "Blue"};

2), this example uses a function to construct an object: note that calling the constructor requires the addition of the new keyword
function person (firstname,lastname,age,eyecolor)
{
This.firstname=firstname;
This.lastname=lastname;
This.age=age;
This.eyecolor=eyecolor;
}

var myfather=new person ("John", "Doe", "Blue");
var mymother=new person ("Sally", "Rally", and "green");

3) Add the method to the JavaScript object
method is simply a function attached to an object.
Methods for defining objects inside the constructor function:
function person (firstname,lastname,age,eyecolor)
{
This.firstname=firstname;
This.lastname=lastname;
This.age=age;
This.eyecolor=eyecolor;

This.changename=changename;
function ChangeName (name)
{
This.lastname=name;
}
}

The 16.avaScript for...in statement loops through the properties of the object. (The code blocks in the for...in loop are executed once for each property.) )
var person={fname: "Bill", lname: "Gates", age:56};

for (x in person)
{
Txt=txt + person[x];
}
Txt=billgates56

17. Date Object:
Date Created:
var d=new date ()//current date and time
var d=new date (milliseconds)//returns the number of milliseconds since January 1, 1970
var d=new Date (datestring)
var d=new Date (year, month, day, hours, minutes, seconds, milliseconds)
Set Date
var mydate=new Date ();
Mydate.setfullyear (2010,0,14);

In the following example, we set the Date object to a date after 5 days:
var mydate=new Date ();
Mydate.setdate (Mydate.getdate () +5);

Some common methods of date objects
var x1=d.getday (); Go back the current date for the first day from Sunday to Saturday, respectively for 0~6
var x2=d.getfullyear (); Get year 2014
var x3=d.gettime (); Returns the number of milliseconds since January 1, 1970.
var h=today.gethours (); Get hours
var m=today.getminutes (); Get minutes
var s=today.getseconds ();//Gets the number of seconds

Show time on page:
<script>
function StartTime ()
{
var today=new Date ();
var h=today.gethours ();
var m=today.getminutes ();
var s=today.getseconds ();
Add a zero in front of numbers<10
M=checktime (m);
S=checktime (s);
document.getElementById (' txt '). innerhtml=h+ ":" +m+ ":" +s;
T=settimeout (function () {startTime ()},500);
}

function Checktime (i)
{
if (i<10)
{
I= "0" + i;
}
return i;
}
</script>

Call StartTime () in onload

18. JavaScript Array (Array) object:
There are three ways to create an array.
1: Conventional way:
var mycars=new Array ();
Mycars[0]= "Saab";
Mycars[1]= "Volvo";
Mycars[2]= "BMW";
2: Simple way:
var mycars=new Array ("Saab", "Volvo", "BMW");
3: literally:
var mycars=["Saab", "Volvo", "BMW"];

accessing arrays
var name=mycars[0];

You can have different objects in an array
All JavaScript variables are objects. An array element is an object. The function is an object.
Therefore, you can have different types of variables in the array.
You can include object elements, functions, and arrays in an array:
Myarray[0]=date.now;
Myarray[1]=myfunction;
Myarray[2]=mycars;

Array methods and properties
Pre-defined properties and methods using array objects:
var x=mycars.length//The number of elements in Mycars
var y=mycars.indexof ("Volvo")//The index position of "Volvo"

Common Array Methods:
var fruits = ["Banana", "Orange", "Apple", "Mango"];

1. Merging arrays
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = Hege.concat (stale);

2. Using elements of an array to form a string
X.innerhtml=fruits.join ();

3. Delete the last element of the array-pop ()
Fruits.pop ();

4. Add a new element at the end of the array-push ()
Fruits.push ("Kiwi")

5. Sort the order of the elements in an array-reverse ()
Fruits.reverse ();

6. Delete the first element of the array-shift ()
Fruits.shift ();

7. Array sort (ascending in alphabetical order)-sort ()
Fruits.sort ();

8. Sort by number (ascending in numeric order)-sort ()
var points = [40,100,1,5,25,10];
Points.sort (function (A, b) {return-A-b});

9. Sort by number (descending in numeric order)
var points = [40,100,1,5,25,10];
Points.sort (function (A, b) {return b-a});

20, JS in the Boolean object

A Boolean object represents two values: "True" or "false"

The following code defines a Boolean object named Myboolean:
var myboolean=new Boolean ();

If the Boolean object has no initial value or its value is:

0
-0
Null
""
False
Undefined
NaN

Then the value of the object is false. Otherwise, its value is true, even when the argument is the string "false"

21. JavaScript Math (Arithmetic) object

1. Rounding
Math.Round (2.5); 3

2.
How do I use random () to return a random number between 0 and 1.
var x= math.random (); 0.5183624960362349

3. Take a larger value in two numbers
Math.max (5,10); 10

4, Math.min (5,10); 5

22. JavaScript RegExp Object
Grammar:
var patt=new RegExp (pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;

The pattern describes an expression model.
Modifiers are used to perform case-insensitive and full-text searches.
The i-modifier is used to perform a case-insensitive match.
The G-modifier is used to perform a full-text search (instead of finding the first one to stop looking, but to find all matches).

Test ()
The test () method searches the string for the specified value, depending on the result and returns TRUE or false.
var patt1=new RegExp ("E");
document.write (Patt1.test ("The best things in life is free"); Returns True

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.
var patt1=new RegExp ("E");
document.write (Patt1.exec ("The best things in life is free"); Return E


Browser object Model (BOM)

23. Window Object
Window objects are supported by all browsers. It represents a browser window.
All JavaScript global objects, functions, and variables automatically become members of the Window object.
A global variable is a property of a Window object.
A global function is a method of a Window object.
Even the document of the HTML DOM is one of the properties of the Window object:

There are three ways to determine the size of the browser window (the viewport of the browser, excluding toolbars and scroll bars).
var w=window.innerwidth
|| Document.documentElement.clientWidth
|| Document.body.clientWidth;

var h=window.innerheight
|| Document.documentElement.clientHeight
|| Document.body.clientHeight;

Other Window methods

Some other methods:
window.open ()-Open a new window
Window.close ()-Close the current window
Window.moveto ()-Move the current window
Window.resizeto ()-Adjusts the size of the current window

24. The Window.screen object contains information about the user's screen.

Screen.availwidth-Available screen widths
Screen.availheight-The available screen height

25. The Window.location object is used to obtain the address (URL) of the current page and redirect the browser to a new page.

Location.hostname returns the domain name of the web host
Location.pathname returns the path and file name of the current page
Location.port returns the port of the web host (80 or 443)
Location.protocol returns the Web protocol used (HTTP///https://)
The Location.href property returns the entire URL of the current page.
The Location.pathname property returns the path name of the URL.
The location.assign ("url") method loads the new document.

26. The Window.history object contains the history of the browser.

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

27. The Window.navigator object contains information about the visitor's browser.

<script>
TXT = "<p>browser codename:" + Navigator.appcodename + "</p>";
txt+= "<p>browser Name:" + navigator.appname + "</p>";
txt+= "<p>browser Version:" + navigator.appversion + "</p>";
txt+= "<p>cookies Enabled:" + navigator.cookieenabled + "</p>";
txt+= "<p>platform:" + navigator.platform + "</p>";
txt+= "<p>user-agent Header:" + navigator.useragent + "</p>";
txt+= "<p>user-agent language:" + navigator.systemlanguage + "</p>";
document.getElementById ("Example"). Innerhtml=txt;
</script>

28. JavaScript Pop-up window
You can create three message boxes in JavaScript: A warning box, a confirmation box, and a prompt box.

Warning Box
Warning boxes are often used to ensure that users can get some information.
When the warning box appears, the user needs to click the OK button to continue the operation.
Grammar
Window.alert ("Sometext");
The Window.alert () method can directly use the alert () method without taking the window object.


Confirmation box
A confirmation box is typically used to verify that a user action is accepted.
When the confirmation card pops up, the user can click "Confirm" or "Cancel" to determine the user action.
When you click "Confirm", the confirmation box returns true and if you click "Cancel", the confirmation box returns false. Grammar
Window.confirm ("Sometext");
The Window.confirm () method can directly use the Confirm () method without taking the window object.

Prompt box
The prompt box is often used to prompt the user to enter a value before entering the page.
When the prompt box appears, the user needs to enter a value and then click the Confirm or Cancel button to continue the manipulation.
If the user clicks Confirm, then the return value is the value entered. If the user clicks Cancel, the return value is null.
Grammar
Window.prompt ("Sometext", "DefaultValue");
The Window.prompt () method can directly use the prompt () method without taking the window object.

Line break
The pop-up window uses a backslash + "n" to set the line break.
Instance
Alert ("Hellon\nhow is You?");

29. JavaScript Timing Events

By using JavaScript, we have the ability to execute code after a set interval of time, not immediately after the function is called. We call this a timing event.

It is easy to use timing events in JAVASCRITP, and two key methods are:

SetInterval ()-interval specifies the number of milliseconds to execute the specified code continuously.
SetTimeout ()-executes the specified code after pausing the specified number of milliseconds
SetInterval () and SetTimeout () are the two methods of the HTML DOM window object.
The first argument is a function
The number of milliseconds for the second parameter interval

Stop execution:
The Clearinterval () method is used to stop the function code executed by the SetInterval () method.
The Cleartimeout () method is used to stop executing the function code of the SetTimeout () method.

30. JavaScript Cookies
Cookies are used to store user information for Web pages.
JavaScript can use the Document.cookie property to create, read, and delete cookies.

In JavaScript, create a cookie as follows:
Document.cookie= "Username=john Doe";
You can also add an expiration time (in UTC or GMT) to the cookie. By default, cookies are deleted when the browser is closed:
Document.cookie= "Username=john Doe; Expires=thu, Dec 12:00:00 GMT ";
You can tell the path to the browser cookie using the path parameter. By default, the cookie belongs to the current page.
Document.cookie= "Username=john Doe; Expires=thu, Dec 12:00:00 GMT; path=/";

Using JavaScript to read cookies
var x = Document.cookie;
Document.cookie will return all cookies in a string, type format: Cookie1=value; Cookie2=value; Cookie3=value;

Using JavaScript to modify cookies

In JavaScript, modifying cookies is similar to creating cookies, as follows:
Document.cookie= "Username=john Smith; Expires=thu, Dec 12:00:00 GMT;  path=/"; The old cookie will be overwritten.

Delete cookies using JavaScript

Deleting cookies is very simple. You only need to set the expires parameter to the previous time, as shown below, set to Thu, 1970 00:00:00 GMT:
Document.cookie = "username=; Expires=thu, 1970 00:00:00 GMT "; Note that you do not have to specify a value for the cookie when you delete it.

Cookie string
The Document.cookie property looks like a normal text string, but it is not.
Even if you write a full cookie string in Document.cookie, the cookie information is displayed as a name/value pair when you re-read the cookie information.
If you set up a new cookie, the old cookie will not be overwritten. The new cookie will be added to Document.cookie, so if you re-read Document.cookie, you will get the data as shown below:
Cookie1=value; Cookie2=value;

Demo
<! DOCTYPE html>
<script>

function Setcookie (cname,cvalue,exdays)
{
var d = new Date ();
D.settime (D.gettime () + (exdays*24*60*60*1000));
var expires = "expires=" +d.togmtstring ();
Document.cookie = cname+ "=" +cvalue+ "; "+expires;
}

function GetCookie (CNAME)
{
var name = cname + "=";
var ca = Document.cookie.split (';');
for (var i=0; i<ca.length; i++)
{
var c = Ca[i].trim ();
if (c.indexof (name) ==0) return c.substring (name.length,c.length);
}
Return "";
}

function Checkcookie ()
{
var User=getcookie ("username");
if (user!= "")
{
Alert ("Welcome again" + user);
}
Else
{
user = prompt ("Please enter your name:", "");
if (user!= "" && user!=null)
{
Setcookie ("username", user,30);
}
}
}

</script>
<body onload= "Checkcookie ()" >
</body>

JS Common built-in objects, Dom objects, BOM objects

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.