JavaScript Common function collation

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

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/1884869

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.