JavaScript Common functions _javascript techniques

Source: Internet
Author: User
Tags abs floor function getdate natural logarithm square root tagname time interval javascript array

JavaScript functions can be divided into five categories altogether:
• General functions
• Array functions
• Date function
• Mathematical Functions
• String Functions
1. General functions
The JavaScript general functions include the following 9 functions:
(1) Alert function: Displays a warning dialog box, including an OK button.
(2) Confirm function: Displays a confirmation dialog box, including OK, Cancel button.
(3) Escape function: Converts a character to a Unicode code.
(4) Eval function: Evaluates the result of an expression.
(5) isNaN function: Test is (true) No (false) is not a number.
(6) parsefloat function: Converts a string into a character point number form.
(7) parseint function: Converts a string into an integer number form (you can specify a few).
(8) Prompt function: Displays an input dialog box that prompts for user input. For example:
<script language= "JavaScript" >
<!--
Alert ("Input error");
Prompt ("Please enter your name", "name");
Confirm ("OK no!") ");
-->
Script>
(9) Unescape function: Decodes characters encoded by the escape function.
2. Array function
The JavaScript array functions include the following 4 functions:
(1) Join function: Converts and joins all elements in an array into a string. Cases:
function Joindemo ()
{
var a, B;
A = new Array (0,1,2,3,4);
b = A.join ("-");//Separator
return (b);/returned b== "0-1-2-3-4"
}
(2) Function: Returns the length of the array. Cases:
function Lengthdemo ()
{
var a, l;
A = new Array (0,1,2,3,4);
L = a.length;
return (l);//l==5
}
(3) Reverse function: Reverses the order of the array elements. Cases:
function Reversedemo ()
{
var a, l;
A = new Array (0,1,2,3,4);
L = A.reverse ();
return (L);
}
(4) Sort function: Reorder the elements of an array. Cases:
function Sortdemo ()
{
var a, l;
A = new Array ("X", "Y", "D", "Z", "V", "M", "R");
L = A.sort ();
return (L);
}
3. Date function
The JavaScript date function includes the following 20 functions:
(1) getdate function: Returns the "Day" section of the date, and the value is 1~31. Cases:
function Datedemo ()
{
var d, s = "Today's" date is: ";
D = new Date ();
S + + (D.getmonth () + 1) + "/";
S + + d.getdate () + "/";
S + + d.getyear ();
return (s);
}
(2) Getday function: Returns the day of the week, the value is 0~6, of which 0 means Sunday, 1 means Monday, ..., 6 means Saturday. Cases:
function Datedemo ()
{
var d, Day, X, S = "Today is:";
var x = new Array ("Sunday", "Monday", "Tuesday");
var x = X.concat ("Wednesday", "Thursday", "Friday");
var x = x.concat ("Saturday");
D = new Date ();
Day = D.getday ();
Return (s + + x[day]);
}
(3) Gethouse function: Returns the "Hour" section of the date, and the value is 0~23. Cases.
function Timedemo ()
{
var d, s = "The current Local:";
var c = ":";
D = new Date ();
S + + d.gethours () + C;
S + + d.getminutes () + C;
S + + d.getseconds () + C;
S + + d.getmilliseconds ();
return (s);
}
(4) Getminutes function: Returns the "Minutes" section of the date, and the value is 0~59. See the above example.
(5) GetMonth function: Returns the "month" section of the date, and the value is 0~11. Of these, 0 said January, 2 means March, ..., 11 means December. See the previous example.
(6) Getseconds function: Returns the "Seconds" section of the date, and the value is 0~59. See the previous example.
(7) GetTime function: Returns the system time.
function Gettimetest ()
{
var d, S, t;
var Minmilli = 1000 * 60;
var Hrmilli = Minmilli * 60;
var Dymilli = Hrmilli * 24;
D = new Date ();
t = D.gettime ();
s = "It ' s Been"
S + + Math.Round (T/dymilli) + "days since 1/1/70";
return (s);
}
(8) getTimezoneOffset function: Returns the time difference for this region (local times and GMT Greenwich Mean time interval), in minutes.
function Tzdemo ()
{
var d, tz, S = "The current local time is";
D = new Date ();
TZ = D.gettimezoneoffset ();
if (TZ < 0)
S + + tz/60 + "hours before GMT";
else if (TZ = 0)
S + + "GMT";
Else
S + + tz/60 + "hours after GMT";
return (s);
}
(9) GetYear function: Returns the "Year" section of the date. The return value is based on a 1900-year base, for example, 1999 is 99. There are examples ahead.
(a) Parse function: Returns the number of milliseconds (local time) from January 1, 1970 zero.
function Gettimetest (testdate)
{
var d, S, t;
var Minmilli = 1000 * 60;
var Hrmilli = Minmilli * 60;
var Dymilli = Hrmilli * 24;
D = new Date ();
t = Date.parse (testdate);
s = "There are"
S + + Math.Round (Math.Abs (T/dymilli)) + "Days"
S + + "between" + TestDate + "and 1/1/70";
return (s);
}
(one) setdate function: Set the date of the "Day" section, the value is 0~31.
sethours function: The "hour" section of the set date, and the value is 0~23.
(setminutes function: The "Minutes" section of the set date, and the value is 0~59.)
setmonth function: The "month" section of the set date, and the value is 0~11. Of these, 0 said January, ..., 11 means December.
setseconds function: The "Seconds" section of the set date, and the value is 0~59.
(settime) Function: Set time. The time value is the number of milliseconds from the whole of January 1, 1970 zero.
(setyear) function: The "Year" section of the set date.
(togmtstring) Function: convert date to string, GMT Greenwich Standard Time.
setlocalestring function: The conversion date becomes a string, local time.
(20) UTC function: Returns the number of milliseconds from the January 1, 1970 zero, calculated as GMT Greenwich Mean time.
4. Mathematical Functions
The JavaScript math function is actually the math object, which includes two parts: attributes and Functions (or methods). Among them, the attributes mainly have the following content.
Math.e:e (natural logarithm), MATH.LN2 (natural logarithm of 2), MATH.LN10 (natural logarithm of 10), math.log2e (the logarithm of E, base 2),

MATH.LOG10E (logarithm of E, base 10), Math.PI (π), math.sqrt1_2 (square root of 1/2), Math.sqrt2 (square root of 2).
The function has the following 18:
(1) ABS function: That is, Math.Abs (in the same below), returns the absolute value of a number.
(2) ACOs function: Returns the inverse cosine of a number, resulting in 0~π radians (radians).
(3) ASIN function: Returns the inverse string value of a number, the result is-Π/2~Π/2 radians.
(4) Atan function: Returns the tangent value of a number, the result is-Π/2~Π/2 radians.
(5) ATAN2 function: Returns the polar coordinate angle value of a coordinate.
(6) Ceil function: Returns the smallest integer value (greater than or equal to) of a number.
(7) Cos function: Returns the cosine of a number, the result is -1~1.
(8) Exp function: Returns the exponentiation value of E (natural logarithm).
(9) Floor function: Returns the maximum integer value of a number (less than or equal to).
Log function: A natural logarithmic function that returns the natural logarithm (e) value of a number.
(one) Max function: Returns the maximum value of two digits.
Min function: Returns the minimum value of two digits.
(POW) Function: Returns the value of a number's exponentiation.
(random) Function: Returns a random number of 0~1.
(round) Function: Returns the rounded value of a number, which is an integer.
Sin function: Returns the sine of a number, and the result is -1~1.
(sqrt) function: Returns the square root value of a number.
Tan function: Returns the tangent value of a number.
5. String function
The JavaScript string function completes operations on the font size, color, length, and lookup of a string, including the following 20 functions:
(1) Anchor function: Create a link point (anchor) for use as a hyperlink. The name of the chain contact set by the anchor function, and the URL address set by the other function link.
(2) Big function: Add the font to a number, with ... The label results are the same.
(3) Blink function: Make string flicker, with ... The label results are the same.
(4) Bold function: Make font bold, with ... The label results are the same.
(5) Charat function: Returns a character specified in the string.
(6) Fixed function: Set the font to a fixed-width font, with ... The label results are the same.
(7) FontColor function: Set the font color, the same as the label results.
(8) FontSize function: Set the font size, the same as the label results.
(9) IndexOf function: Returns the first found subscript index in the string, starting from the left.
(a) Italics function: Make font italic, with ... The label results are the same.
(one) LastIndexOf function: Returns the first found subscript index in the string, starting from the right.
() Length function: Returns the length of a string. (without parentheses)
Link function: Produces a hyperlink that corresponds to a set URL address.
(small) function: Reduce the font by one number, with ... The label results are the same.
(strike) Function: Add a horizontal line to the middle of the text, and ... The label results are the same.
Sub function: Displays a string as the subscript (subscript).
(substring) Function: Returns a number of characters specified in a string.
(a) SUP function: Display string as superscript (superscript).
(tolowercase) Function: Converts a string to lowercase.
toUpperCase function: Converts a string to uppercase.

Event Source Object
Event.srcElement.tagName
Event.srcElement.type

Capture Release
Event.srcElement.setCapture ();
Event.srcElement.releaseCapture ();

Event Key
Event.keycode
Event.shiftkey
Event.altkey
Event.ctrlkey

Event return value
Event.returnvalue

Mouse Position
Event.x
Event.y

form activity Elements
Document.activeelement

Binding Events
Document.captureevents (Event.keydown);

Accessing form elements
document.all ("TXT"). focus ();
document.all ("TXT"). Select ();

Form Command
Document.execcommand

form Cookies
Document.cookie

Menu Events
Document.oncontextmenu

Creating Elements
Document.createelement ("SPAN");

get elements from the mouse
Document.elementfrompoint (EVENT.X,EVENT.Y). tagname== "TD
Document.elementfrompoint (EVENT.X,EVENT.Y). appendchild (MS)

form Picture
document.images[Index]

form Event Bindings
Document.onmousedown=scrollwindow;

element
Document. Forms. Elements[index]

Object Binding Events
Document.all.xxx.detachEvent (' onclick ', a);

Number of Plug-ins
Navigator.plugins

take variable type
typeof ($js _libpath) = = "Undefined"
Drop down box
Dropdown box. options[Index]
Drop-down box. Options.length

Finding Objects
Document.getelementsbyname ("R1");
document.getElementById (ID);

timed
Timer=setinterval (' ScrollWindow () ', delay);
Clearinterval (timer);

Uncode Code
Escape (), unescape

Parent Object

Obj.parentelement (DHTML)
Obj.parentnode (DOM)

exchange Table Rows
Tableid.moverow (2,1)//swap the third row with the second line

Replace CSS
Document.all.csss.href = "A.css";

Show Side
Display:inline

Hide Focus
Hidefocus=true

Wrap line by width

Style= "Word-break:break-all"

Auto Refresh
<meta http-equiv= "Refresh" content= "8; Url=http://hi.baidu.com ">

Simple Mail
<a href= "Mailto:jishu@bj08ay.cn?subject=thisistitle&body=thisisthewordswhatyouwanttowriteforme" >

Quick go to position

Obj.scrollintoview (True)

Anchor

<a name= "a" >
<a href= "#first" >anchors</a>

Page Pass Parameters

Location.search ();

can be edited

Obj.contenteditable=true

Execute menu Command

Obj.execcommand

Double Byte character

/[^\x00-\xff]/

Chinese characters

/[\u4e00-\u9fa5]/

Wrap the English string beyond the table width
Word-wrap:break-word; Word-break:break-all;

Transparent Background

<iframe src= "1.htm" width=300 height=180 allowtransparency></iframe>

Get style content
Obj.style.cssText

HTML Tags
Document.documentElement.innerHTML

First style label
Document.stylesheets[0]

the first style in the Styles tab
Document.stylesheets[0].rules[0]

prevents clicking on the empty link, the page is often reset to the top of the page.
<a href= "javascript:function ()" >word</a>

Previous page Source

Asp:
Request.ServerVariables ("Http_referer")
Javascript:
Document.referrer

Free Memory
CollectGarbage ();

No right key

Document.oncontextmenu = function () {return false;}

Prohibit save
<noscript><iframe src= "*.htm" ></iframe></noscript>

Prohibit selection
<body oncontextmenu= ' return false ' ondragstart= ' return false ' Onselectstart = ' return false ' onselect= ' Document.selection.empty () "oncopy=" Document.selection.empty () "onbeforecopy=" return false "onmouseup=" Document.selection.empty () >

No paste

<input Type=text onpaste= "return false" >

Address bar icon
<link rel= "Shortcut Icon" href= "Favicon.ico" >
Favicon.ico name best unchanged 16*16 16 color, put the virtual directory root directory

Favorites Bar Icon

<link rel= "Bookmark" href= "Favicon.ico" >

View Source

<input type=button value= View Web page source code onclick= "window.location = ' view-source: ' + ' http://www.csdn.net/'" >

Close IME
<input style= "ime-mode:disabled" >

Auto Select All
<input type=text name=text1 value= "123" onfocus= "This.select ()" >

Enter to move the cursor to the next input box
<input onkeydown= "if (event.keycode==13) event.keycode=9" >

default values for text boxes
<input type=text value= "123" onfocus= "alert (this.defaultvalue)" >

the microseconds represented by the acquisition of Time
var n1 = new Date ("2004-10-10". Replace (/-/g, "\/")). GetTime ()

whether the window is closed
Win.closed

checkbox Flat
<input type=checkbox style= "Position:absolute; Clip:rect (5px 15px 15px 5px) "><br>

Get the selection
Document.selection.createRange (). Duplicate (). Text

Auto Completion function
<input Type=text autocomplete=on> to open this feature
<input type=text autocomplete=off> Turn off this feature

window Maximization
<body onload= "Window.resizeto (window.screen.width-4,window.screen.height-50) window.moveTo ( -4,-4)" >

no Close button ie
window.open ("aa.htm", "Meizz", "fullscreen=7");

Unified Coding/decoding
Alert (decodeuricomponent encodeuricomponent ("http://hello. com?as= hehe"))
encodeURIComponent to ":", "/", ";" and "?" Also encoded

table row indicates
<tr onmouseover= "this.bgcolor= ' #f0f0f0" "onmouseout=" this.bgcolor= ' #ffffff ' ">

various sizes
s + = "\ r \ n page visible area wide:" + document.body.clientWidth;
s + + "\ r \ n page visible Area High:" + document.body.clientHeight;
s + + "\ r \ n" page visible area High: "+ Document.body.offsetWeight +" (including the edge of the width);
s + + "\ r \ n" page visible area High: "+ Document.body.offsetHeight +" (including the edge of the width);
s + + "\ r \ n page text full text width:" + document.body.scrollWidth;
s + + "\ r \ n" page full text High: "+ document.body.scrollHeight;
s + + "\ r \ n Pages are rolled High:" + document.body.scrollTop;
s + + "\ r \ n page is rolled to the left:" + document.body.scrollLeft;
s + + "\ r \ n Page body part:" + window.screentop;
s + + "\ r \ n Page body part left:" + window.screenleft;
s + + "\ r \ n screen resolution of High:" + window.screen.height;
s + + "\ r \ n Screen resolution width:" + window.screen.width;
s + = "\ r \ n Screen available working area height:" + window.screen.availHeight;
s + = "\ r \ n Screen available working area width:" + window.screen.availWidth;

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.