Javascript Common Code Summary

Source: Internet
Author: User
Tags cos sin javascript array

1. Document.referrer can get the address of the previous page and use Document.anchors to get all the link elements on the page without having to use document.getElementsByTagName (' A '); The same reason is document.forms, document.images.

2. Function.length--The number of parameters defined, such as function AA (A,B,C)--aa.length = 3

3. Arguments [function.] Arguments[n] The arguments of the function being executed and the function that called it

It is necessary to note that arguments is not an array and can be instanceof tested.
Alert (arguments instanceof Array)//false

4. The Apply method can hijack another object's method, inheriting another object's properties.
Alert (Math.max (5,8))//8
var arr=[5,7,9,1]
Alert (Math.max (ARR))//This is not possible. must be written in circular judgment
--Math.max.apply (Null,arr)//can calculate the maximum value in this array
--Array.prototype.push.apply (ARR1,ARR2)//Append the elements of the array arr2 to the ARR1
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the wording of the Apply: Func.apply (Func1,[var1,var2,var3])
Person.apply (this,arguments)
The benefit of using apply at the same time is that you can directly pass in the arguments object of the current function as the second parameter of apply
Call invokes one method of an object, replacing the current object with another object.

5. The typeof operator returns the type information as a string. There are six possible typeof return values: "Number," "String," "Boolean," "Object," "function," and "undefined."

6. See the picture immediately after uploading

Detect picture File size

if (document.filesize)
{Alert (parseint (document.images.oimg.filesize,10)})
Else
{Alert ("Browser does not support this feature.) ")}
Emptying the input file value
document.getElementById (' <%=fuFilesUpload.ClientID%> '). outerHTML = document.getElementById (' <%
=fufilesupload.clientid%> '). outerHTML;

7. js function
Replacing replace ("", "")--can only replace the first match--and change to regular. Replace (/-/g, "/") will all "-" be replaced with "/"
Combine with function: Capitalize all the first letters of the word
var StrM = "JavaScript is a good script language";
function Change (Word)
{
Return Word.indexof (0). toUpperCase () +word.substring (1);
}
Alert (Strm.replace (/\b\w+\b/g,change));

Split string: Split ("-")
Connection string: Strobj.concat (stringx,stringx,..., stringx) [available for arrays]
is a finite number: Isfinite
Not numbers: IsNaN (number) [Not a No.]
String plus decryption: Escape () and unescape ()
URI encryption: encodeURI (uristring) encodeURI ("http://w.p.m?a= China"), Http://www.w3pop.com?a=%E4%B8%AD%E5%9B%BD
URI decryption: decodeURI (uristring)
Parsefloat (String) returns the number of floating-point numbers that are converted by a string.
The Parsefloat method returns a numeric representation that is equal to the number saved in numstring.
If the prefix of the numstring cannot be interpreted as a floating-point number, NaN (not a digit) is returned.
Parsefloat ("abc")//Return NaN. Parsefloat ("1.2ABC")//Return 1.2.
parseint (string, radix) converts a string to an integer number other ibid.
Radix: Binary 2 to 36 16 binary 10 binary parsefloat ("1.2ABC")//return 1.
---transformation---
Number (object) is converted to numeric
String (object) is converted to strings
Strobj.tolowercase () Lowercase string
Strobj.touppercase () Uppercase string
---Find the Intercept string aspect---
Strobj.indexof (Searchvalue,fromindex) returns the position of the first occurrence of the specified value in the string, or 1 if no substring is found. Fromindex an optional integer parameter. Specifies where to start retrieving in the string. Its legal value is 0 to stringobject.length-1. If this argument is omitted, it is retrieved from the first character of the string.
Strobj.lastindexof () returns the position of the last occurrence of the specified string in the string, and the search direction is backward.
Strobj.match (Searchvalue) finds the specified value from the string, returns the specified value, and cannot find a return null
Strobj.search (searchstring) looks for the position of the specified value from the string, finds the position returned in the string, and cannot find the return-1 [Search ("AA") |search (/aa/)]
Fuzzy match plus I [Search (/aa/i)] "/xxx/"-Regular expression pattern
Strobj.slice (start,end) selects a subset of characters from a string and returns them as a new string
You can select a character from the end of the string with a negative start value
STROBJ.SUBSTR (start,length) selects a specified length of character from a string from the specified starting position
Strobj.substring (start,stop) characters between specific locations
Strobj.slice (start,end) extracts some characters and returns the remainder in a new string
----style aspects---
Strobj.sup () superscript string such as square
Strobj.sub () string displayed as subscript
Strobj.small () displays a string with a small number
Strobj.big () displays a string with a large number
The Strobj.strike () string is displayed in the form of a delete
Strobj.blink () Displays the flashing string firefox,netscape
Strobj.bold () displays bold string
Strobj.fontcolor (color) specifies a colored display string
Strobj.fontsize (size) Specifies the font size of the display string
Strobj.italics () displaying strings in italics
The Strobj.link () string is displayed as a hyperlink

---
system function
New Open with window: window.open ("/page/zulin/tz/jgd_chuli.aspx");
Back: Window.history.go (-1);
Close window: window.close ()
Confirmation dialog box: if (window.confirm ("Are you sure?")) {}else{}
dialog box with input: window.prompt ("Please enter your name", ""); method return value is the value entered
Clipboard: Window.clipboardData.setData ("Text", url);
Automatic Call Method 1:window.settimeout (Vcode, milliseconds) executes 1 times 1000 milliseconds for one second
Clear automatic call: Cleartimeout (Vcode)
Automatically calls Method 2: Window.setinterval (Vcode, Imilliseconds [, Slanguage]) executes Imilliseconds
Clear automatic calls every Vcod (clearinterval)
---
window.location.reload () Refresh
Location.hash set or get the segment after the pound sign "#" in the href attribute.
Location.host set or get the hostname and port numbers for the location or URL.
Location.hostname Sets or gets the host name portion of the location or URL. The
Location.href sets or gets the entire URL as a string. The
Location.pathname sets or gets the file name or path specified by the object. The
Location.port sets or gets the port number associated with the URL. The
Location.protocol sets or gets the protocol portion of the URL.
Location.search Sets or gets the portion of the HREF attribute that follows the question mark.

Window.external.AddFavorite (Location.href, Document.title) Favorites
Window.external.ImportExportFavorites (True , Import Favorites
Window.external.ImportExportFavorites (False), export favorites
Window.external.ShowBrowserUI ( Organizefavorites, NULL) Organize favorites
Window.location = "View-source:" + window.location.href View the original file
Window.external.ShowBrowserUI (Languagedialog, NULL) language setting
Window.onbeforeunload event triggers a dialog box with OK and cancel, OK to leave the page, Cancel will continue to stay on this page.
triggered at:
* Close the browser window
* When you go to another page via the Address bar or Favorites
* Click Back, go, refresh, page one of the time
* Click on a URL to the other page to connect the time
* When invoking any of the following events: Click,document write,document open,document close,window Close, window navigate, window Navigateandfind, Location Replace,location Reload,form Submit.
* When opening a page with window open and passing the name of the window on this page to the page to be opened.
* When the value of Location.href is re-assigned.
* When submitting a form with the specified action via the input type= "submit" button.
window.onbeforeunload= "javascript:void";

8. js Event
onkeypress occurs when the user presses and releases any alphanumeric keys. System buttons (for example, arrow keys and Function keys) cannot be identified. [Response to a key]
OnKeyUp occurs when the user releases any previously pressed keyboard keys.
OnKeyDown occurs when the user presses any keyboard key (including system buttons, such as arrow keys and Function keys). [Response to a combination of several keys]
You can respond to the combination of CTRL, ALT, shift, and other function keys and keys, and onkeypress cannot
Onfocusout Loss of cursor events
onfocus Getting cursor Events
Onabort when a picture download is interrupted
When the onblur element loses focus
OnDblClick Mouse Double-click
OnError loading a document or picture when an error occurs
OnMouseDown when the mouse is pressed
OnMouseMove when the mouse is moved
onmouseout when the mouse leaves the element
onmouseover when the mouse passes through an element
OnMouseUp When the mouse button is released
OnUnload when the user leaves the page

9. JS Math Object
Math.Round (x) rounding out and rounding
Math.random () returns a random number between 0 and 1
Math.max (x, y) returns a large number between x and Y
Math.min (x, y) returns the smaller number between x and Y
Math.floor (x) returns the smallest integer after x rounding
Math.ceil (x) returns the largest integer after X rounding
Math.Abs (x) returns the absolute value of a number
Math.pow (x, y) returns the value of Y^x

ScrollHeight: Gets the scroll height of the object.
ScrollLeft: Sets or gets the distance between the leftmost end of the left edge of the object and the currently visible content in the window
ScrollTop: Sets or gets the distance between the top of the object and the top of the visible content in the window
ScrollWidth: Gets the scroll width of the object
Offsetheight: Gets the height of the object relative to the layout or the parent coordinate specified by the parent coordinate OffsetParent property
Offsetleft: Gets the object relative to the canvas or by the offsetParent The
OffsetTop: Gets the calculated top position of the object relative to the layout or parent coordinates specified by the OffsetTop property
Event.clientx The horizontal coordinates of the relative document
Event.clienty The vertical coordinate of the relative document
Event.offsetx the horizontal coordinate of the relative container
event.offsety the vertical coordinates of the container
Document.documentElement.scrollTop the vertical scrolling value
Event.clientx+document.documentelement.scrolltop The horizontal coordinates of the relative document + the amount of scrolling vertically
on the body part of the Web page: Window.screentop
Page body part left: window.screenleft;
High screen resolution: window.screen.height;
Width of screen resolution: Window.screen.width;
Screen usable workspace height: window.screen.availHeight;
Screen Usable workspace width: window.screen.availWidth;
Your screen settings are window.screen.colorDepth + "bit color";
your screen settings Window.screen.deviceXDPI + "pixels per inch";

One. JS Loop
For (...) Statement
var mycars = new Array ();
Mycars[0] = "fa pull"; mycars[1] = "Porsche"; mycars[2] = "BMW;
for (x in Mycars) {document.write (Mycars[x] + "
"); }
while (bool) {;} statement
do{;} while (BOOL) statement
---------
Switch (key) {Case 1:code;break;default:}

JS Error
try{//throw "ERR1"}catch (err) {Err.Description} can catch to throw here and err equals "ERR1"

The. JS with statement sets the default object for the statement.
x = Math.Cos (3 * Math.PI) + math.sin (math.ln10) y = Math.tan (+ * MATH.E)
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
With (Math) {x = cos (3 * PI) + sin (LN10) y = tan (* E)}

14. Disable paste and drag to text box
Onpaste= "Return!clipboarddata.getdata (' text '). Match (/\d/)" ondragenter= "return False"

15. The subform refreshes the parent form
Window.opener.location.reload ();

Mlogon is the button for the parent form

16. Shielding Input Method

. JavaScript to manually trigger the onchange event

. JavaScript array usage
var xpos=new array ()
for (i=0;i<=message.length-1;i++) {
xpos[i]=-50}
Var ypos= New Array () Hubei province
for (i=0;i<=message.length-1;i++) {
Ypos[i]=-50}
(1). var myArray = new Array (); var myArray = [];
(2). var myArray = new Array ("Red", "green", "blue"), or var myArray = ["Red", "green", "blue"];
(3). var MyArray = new Array (3), or var myArray = [,,];
Delete an array element, you can use the delete operator, for example: Delete myarray[1];.
. Length also has a good use, is to delete elements, such as a lot of elements of an array, the user would like to delete all elements, can be used with length, very simple and fast, such as: Myarray.length = 0;.

Strarr.shift () deletes and returns the first element value in the array
Strarr.unshift (item1[,item2[,...]]) adds one or more elements to the beginning of an array, and returns the new length
Strarr.slice (Start,end) returns from an element in an existing array, starting in turn
Strarr.splice (index,howmany,element1,....., elementx) method for inserting, deleting, or replacing elements of an array
Index: Required option. Specifies where to add/remove elements, which must be a number
Howmany: Required option. Specifies how many elements should be deleted. Must be a number, can be "0"
Element1 is optional. Specifies the new element to be added to the array. Start the insertion from the subscript at index point.
Elementx is optional. You can add several elements to an array.
Strarr.sort (sortby) SortBy: Optional must be a functional function sortbynumber (A, b) {return a-B;} [The array itself will change]
Strarr.concat (Arrayx,..., arrayx) combine two or more arrays [return a new array]
Strarr.join (separator) merges all the elements in the array into a single string. Each element can specify their delimiting tags.
Strarr.shift () deletes and returns the first element value in the array [the array itself will change]
Strarr.pop () Delete and return the last element of the array [the array itself will change]
Strarr.push (Newelement1,newelement2,...., newelementx) can add one or more elements to the end of the array and return the new length. [The array itself will change]

Strarr.reverse () array reverse

19. The text box can only enter a number, perfect, but (. 1), (. 001) can be entered as such
onkeypress= "Return event.keycode>=48&&event.keycode<=57| | (This.value.indexOf ('. ') <0?event.keycode==46:false) "

20. If the property disabled of select is set to False, the server side will not get the value when committing
var sn_list = document.getElementById ("Shopname");
var op = new option ("Please choose Store Name", "");
Op.selected = true;
Sn_list.add (OP);

is not all form element settings disabled set to False after the server is not acquired? Pending verification:

21. Replace the string. Replace (new RegExp (",", "GM"), "")

22. Simple prevention of duplicate submission of forms

23. Turn off auto-complete autocomplete= "off"

. js Object
Popobj=new Object ()
Popobj.name= "POP"
Popobj.addr= "Www.w3pop.com"
popobj.tip= "Welcome You"
document.write (Popobj.name + popobj.tip)-->pop welcome you
---
function Mypop (name,addr,tip)
{
This.name=name
This.addr=addr
This.tip=tip
}
Newpop=new Mypop ("POP", "www.w3pop.com", "Welcome You")
document.write (Newpop.name + newpop.tip)-->pop welcome you

. JS Special Characters
\ ' Single quotation mark
\ "Double quotation marks
\& & Symbols
\ \ counter Slash
\ n line break
\ r return character
\ t tab
\b Backspace
\f Page Breaks

window.open window Features
Channelmode=yes|no|1|0 whether to use the theater Mode Display window. The default is No.
Directories=yes|no|1|0 whether to add a directory button. The default is yes.
Fullscreen=yes|no|1|0 whether to use full-screen mode to display the browser. The default is No. A window in full-screen mode must be in theater mode at the same time.
Height=pixels the height of the window document display area. measured in pixels.
The x-coordinate of the Left=pixels window. measured in pixels.
Location=yes|no|1|0 whether the Address field is displayed. The default is yes.
Menubar=yes|no|1|0 whether the menu bar is displayed. The default is yes.
Resizable=yes|no|1|0 whether the window can be adjusted for size. The default is yes.
Scrollbars=yes|no|1|0 whether scroll bars are displayed. The default is yes.
Status=yes|no|1|0 whether to add a status bar. The default is yes.
Titlebar=yes|no|1|0 whether the title bar is displayed. The default is yes.
Toolbar=yes|no|1|0 whether the browser's toolbar is displayed. The default is yes.
The y-coordinate of the Top=pixels window.
The width of the document display area of the Width=pixels window. measured in pixels.

Event.altkey. When the ALT key is pressed, the value is TRUE, otherwise FALSE. Read-only
Event.ctrlkey when the CTRL key is pressed, the value is TRUE, otherwise FALSE. Read-only
Event.shiftkey when the SHIFT key is pressed, the value is TRUE, otherwise FALSE. Read-only.
Event.button This property is only used for onmousedown, onmouseup, and onmousemove events. detects the inner code corresponding to the keyboard event.
0 No buttons.
1 Press the left button
2 Press the right button
3 Press the left and right key
4 Press the Middle key
5 Press the left and middle keys
6 Right-click and Middle-key
7 Press All the keys
Returns 0 (for example, onclick) for other events, regardless of mouse state.
Event.keycode This attribute is used for onkeydown, onkeyup, and onkeypress events.
A read-write value that can be any Unicode keyboard inside code. If no keyboard event is raised, the value is 0.
Event.clientx returns the x-coordinate of the mouse in the client area of the window, read-only property.
Event.clienty returns the y-coordinate of the mouse in the window client area, and the read-only property.
EVENT.OFFSETX check the horizontal coordinates of the mouse position relative to the object that triggered the event
Event.offsety Check the vertical coordinates of the mouse position relative to the object that triggered the event
Event.screenx detects the horizontal position of the mouse relative to the user's screen, read-only properties
Event.screeny detect the vertical position of the mouse relative to the user's screen, read-only properties
Event.x returns the x-coordinate of the mouse relative to the ancestor element with the Position property in the CSS property. If there is no ancestor element with the Position property in the CSS property, the BODY element is used as the reference object by default.
If the mouse moves out of the window after the event is triggered, the value returned is-1, the read-only property.
Event.y Ibid. opposite
Event.srcelement returns the element that triggered the event, read-only.
Event.fromelement detects onmouseover and onmouseout events that occur when the mouse leaves the element. Read-only property.
Event.toelement detects onmouseover and onmouseout events that occur when the mouse enters the element. Read-only property.
event.returnvalue[= Boolean] Sets or checks the value returned from the event, the value in the true event is returned, false the default action of the event on the source object is canceled
Event.type returns the event name. Returns the event name without "on" as the prefix, for example, the type returned by the onclick event is click, read-only.

Transferred from original: http://blog.chinaunix.net/uid-20573208-id-1627692.html

Javascript Common Code Summary

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.