JavaScript Common function collation

Source: Internet
Author: User
Tags abs floor function local time mathematical functions natural logarithm square root

JavaScript functions:


1. Disable the right mouse button menu code block

function Stop () {return false;} Document.oncontextmenu = stop; Disable right mouse button Document.ondragstart = stop; Prohibit drag Document.onselectstart = stop; Prohibit selection



2. Determine if an open page exists on the parent page

if (window.top = = Window.self && window.parent = = Window) {//there is no parent page Alert ("illegal Login forbidden"); Location.href = "/xxx/xxxx/xxxx.htm";//jump page}


3. Add js, CSS reference to the page

document.write (' <script src= '/script/layui1.0.7/layui.js ' type= ' text/javascript ' ></script> ');

4. Read the parameters in the link


Link: http://localhost:83/App/News/News.html?UserCode=00000000;

var usercode = Geturlparam (' usercode '), function Geturlparam (name) {var reg = new RegExp ("(^|&)" + name + "= ([^& amp;] *) (&|$) ");  Constructs a regular expression object containing the target parameter var r = Window.location.search.substr (1). match (reg); Match Target parameter if (r! = Null) return decodeURI (r[2]); Return null; Return parameter value}


5. Jump Page

Window.location.href = Data. Url;


6.JS Setting cookies

JS settings cookiefunction setcookie (name,value) {var days = 30;var exp = new Date (); exp.settime (exp.gettime () + days*24*60*60* ;d Ocument.cookie = name + "=" + escape (value) + "; expires=" + exp.togmtstring ();}


7.JS Read Cookie

JS Read cookiefunction getcookie (name) {var arr,reg=new RegExp ("(^|)" +name+ "= ([^;] *) (; |$) "), if (arr=document.cookie.match (reg)) return unescape (arr[2]); elsereturn null;}

8.JS Delete Cookies

JS Delete cookiefunction Delcookie (name) {var exp = new Date (); exp.settime (exp.gettime ()-1); var cval=getcookie (name); if ( Cval!=null) document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();}


9.JS General functions


JavaScript general functions include the following 10 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: The test is (true) no (false) is not a number.

(6) parsefloat Function: Converts a string into a numeric form of a character.

(7) parseint Function: Converts a string into an integer number form (which can be specified as a binary).

(8) prompt function: displays an input dialog box prompting for user Input.

(9) unescape Function: Decodes characters encoded by the escape Function.

(ten) toFixed function: This function is to convert a few decimal points of checkprice.tofixed (2); convert Checkprice to two decimal places


10. Array Functions


The JavaScript array function consists of the following 5 functions:

(1) Join Function: converts and joins all elements in an array to a string. Cases:

function Joindemo () {var a, b;     A = new Array (0,1,2,3,4); b = A.join ("-");//delimiter return (b);//return b== "0-1-2-3-4"}

(2) length Function: Returns the lengths 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 array elements. Cases:

function Sortdemo () {var a, l;     A = new Array ("X", "y", "d", "Z", "v", "m", "r");     L = A.sort ();    Return (l); }

(5) The push function: adds a new element to an array and returns the new length value of the Array. Cases:


function Pushdemo () {var my_array = new array (' 1 ', ' 2 ', ' 3 ', ' 4 ');      My_array.push (' 5 ', ' 6 ', ' 7 ', ' 8 ');    Alert (my_array.length); Adds 4 elements to the returned 8 array}

11. Date function


The JavaScript date function consists of the following 20 functions:

(1) getdate Function: Returns the day portion of the date, with a value of 1~31.

(2) getday Function: Returns the day of the week with a value of 0~6, where 0 represents Sunday, 1 means Monday, ..., and 6 means Saturday.

(3) gethouse function: Returns the "hour" portion of the date, with a value of 0~23.

(4) getminutes Function: Returns the "minute" part of the date with a value of 0~59. See the example Above.

(5) getmonth function: Returns the month portion of the date, with a value of 0~11. 0 means January, 2 means March, ..., and 11 means December.

(6) getseconds Function: Returns the "second" part of the date with a value of 0~59.

(7) gettime Function: Returns the system Time.

(8) getTimezoneOffset Function: Returns the difference in this area (local time and GMT Greenwich mean time), in Minutes.

(9) getyear Function: Returns the "year" part of the Date. The return value is based on a 1900-year base, for example, 1999 is 99.

Parse Function: returns the number of milliseconds (local Time) that was counted from zero January 1, 1970.

(one) setdate function: The "day" portion of the set date, with a value of 0~31.

sethours function: The "hours" section of the set date, with a value of 0~23.

Setminutes function: The "minutes" section of the set date, with a value of 0~59.

Setmonth function: sets the month portion of the date, and the value is 0~11. 0 of them represent January, ..., 11 means December.

() setseconds function: The "seconds" section of the set date, and the value is 0~59.

() settime Function: Set the Time. The time value is the number of milliseconds since January 1, 1970 when the integer count is zero.

() setyear function: The "year" section of the set Date.

toGMTString function: The conversion date becomes a string, GMT Greenwich standard TIME.

() setlocalestring Function: Converts the date into a string, for local time.

(20) UTC Function: Returns the number of milliseconds from January 1, 1970 to the full count, measured in GMT Greenwich mean TIME.

12. Mathematical Functions


The JavaScript math function is actually the math object, which includes attributes and functions (or Methods) in two Parts. Where the attribute mainly has the following Content.

Math.e:e (natural logarithm), math.ln2 (natural logarithm of 2), math.ln10 (natural logarithm of 10), math.log2e (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 value of 2).

The function has the following 18:

(1) ABS function: Math.Abs (the Same as below), returns the absolute value of a number.

(2) ACOs function: Returns the inverse cosine of a number with a result of 0~π radians (radians).

(3) ASIN Function: Returns the inverse chord value of a number, resulting IN-Π/2~Π/2 radians.

(4) atan function: Returns the inverse tangent of a number, resulting IN-Π/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 with the result of -1~1.

(8) Exp Function: returns the value of the exponent of e (natural logarithm).

(9) floor function: Returns the maximum integer value (less than or equal to) of a number.

Log function: a natural logarithm 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.

Random function: returns a 0~1 Value.

Round function: Returns the rounded value of a number with an integer type.

Sin function: returns the sine of a number with the result of -1~1.

sqrt function: returns the square root value of a number.

Tan Function: Returns the tangent of a number.



13. String Functions


(1) concat function: The text of two or more characters is combined to return a new string.

(2) indexof function: Returns the index (from left to Right) of the first occurrence of a substring in a string. If there is no match, returns-1.

(3) LastIndexOf: Returns the index (right-to-left Search) at the first occurrence of a substring in a string. If there is no match, returns-1.

(4) CharAt: Returns a character specified in the String.

(4) Match: checks a string to match a regular expression content, if there is a match return Null.

(5) Substring: returns a substring at the specified position in a string object.

(6) Substr: Returns a substring of a string in which the incoming parameter is the starting position and length

(7) Replace: used to find a string that matches a regular expression, and then use the new string instead of the matching string.

(8) Search: performs a regular expression matching Lookup. If the lookup succeeds, returns the matching index value in the String. otherwise returns-1.

(9) slice: extracts part of a string and returns a new string (same as Substring).

Split: A string is made into a string array by dividing the string into substrings.

(one) Length: Returns the length of the string, which is the number of characters it contains.

Tolowercase: converts the entire string into lowercase letters.

Touppercase: turns the entire string into Uppercase.


14.JS printing content in a specific div


Function print ()  {           var headstr  =  "


15.HTML5 Get Mobile Location


Function getlocation ()  {            if   (navigator.geolocation)  {                 navigator.geolocation.getcurrentposition (showposition, showerror);             } else {                 alert ("the Browser does not support Geo-targeting. ");            }         }        function showerror (error)  {             switch  (error.code)  {                 case error. permission_denied:                    alert ("location failed, user refused to request geo-location");                      break;                 Case error. position_unavailable:                     alert ("location failed, Position information is not available");                     break;                 case error. timeout:                     alert ("location failed, Request get user location timeout");                     break;                 case error. unknown_error:                     alert ("location failure, Location System failure");                     break;             }        }         function showposition (position)  {             lat = position.coords.latitude; //latitude               lag = position.coords.longitude; //longitude               alert (' latitude: '  + lat +   ', Longitude: '  + lag);                     }


This article from "dream blossom, dream fly" blog, Please be sure to keep this source http://wppeng.blog.51cto.com/9894483/1884871

JavaScript Common function collation

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.