Common. js methods in projects

Source: Internet
Author: User

Common. js methods in projects

Take the time to organize the common js methods in the project into common. js, which are collected on the Internet. Let's share with you.

 

Var h = {}; h. get = function (url, data, OK, error) {$. ajax ({url: url, data: data, dataType: 'json', success: OK, error: error});} h. post = function (url, data, OK, error) {$. ajax ({url: url, data: data, type: 'post', dataType: 'json', success: OK, error: error });} // obtain the url parameter h. url = function (url) {if (! Url) {url = location. search. substring (1);} else {url = url. substr (url. indexOf ('? ') + 1);} var args = new Object (); // declare and initialize a "class" // get address (URL )"? "String. var query = decodeURI (url); var pairs = query. split ("&"); // split the URL (don't forget '&' is used to connect to the next parameter) for (var I = 0; I <pairs. length; I ++) {var pos = pairs [I]. indexOf ('='); if (pos =-1) continue; // It is looking for an array with equal signs [I] var argname = pairs [I]. substring (0, pos); // parameter name var value = pairs [I]. substring (pos + 1); // parameter value // It is stored as a key-value pair in the "args" object. args [argname] = decodeURI (value );} return args;} // returns the actual length of the string. A Chinese character is counted as 2. Length String. prototype. strlen = function () {return this. replace (/[^ \ x00-\ xff]/g ,"**"). length;} // The String exceeds the omitted String. prototype. cutstr = function (len) {var restr = this; var wlength = this. replace (/[^ \ x00-\ xff]/g ,"**"). length; if (wlength> len) {for (var k = len/2; k <this. length; k ++) {if (this. substr (0, k ). replace (/[^ \ x00-\ xff]/g ,"**"). length> = len) {restr = this. substr (0, k) + "... "; break; }}} Return restr;} // replace all strings. prototype. replaceAll = function (s1, s2) {return this. replace (new RegExp (s1, "gm"), s2)} // String to remove space String. prototype. trim = function () {return this. replace (/(^ \ s *) | (\ s * $)/g, "");} String. prototype. trimAll = function () {return this. replace (/\ s +/g, "");} String. prototype. lTrim = function () {return this. replace (/(^ \ s *)/g, "");} String. prototype. rTrim = function (){ Return this. replace (/(\ s * $)/g, "") ;}// determine whether to start with a String. prototype. startWith = function (s) {return this. indexOf (s) = 0} // determines whether to end the String with a certain String. prototype. endWith = function (s) {var d = this. length-s. length; return (d> = 0 & this. lastIndexOf (s) = d)} // Delete the repeated element function getUnique (someArray) {tempArray = someArray. slice (0); // copy the array to the temporary array for (var I = 0; I <tempArray. length; I ++) {for (var j = I + 1; j <tempArray. length;) {if (tempArray [j] = tempArray [I]) // if the elements are the same as those to be compared, they are deleted and counted. // after deletion, the following elements are automatically advances, so the pointer j is not moved {tempArray. splice (j, 1) ;}else {j ++ ;}// different, the pointer moves} return tempArray ;} // function confirmRepeat (someArray) {tempArray = someArray. slice (0); // copy the array to the temporary array for (var I = 0; I <tempArray. length; I ++) {for (var j = I + 1; j <tempArray. length;) {if (tempArray [j] = TempArray [I]) // if the elements following the tempArray are the same as those to be compared, they are deleted and counted. // after deletion, the elements following the tempArray are automatically advanced, so the pointer j does not move {return true;} else {j ++;} // different, then the pointer moves} return false ;} // determine whether a value is in the Array. prototype. in_array = function (e) {for (I = 0; I <this. length; I ++) {if (this [I] = e) return true;} return false;} // judge the position of a value in the Array. prototype. indexOf = function (e) {for (I = 0; I <this. length; I ++) {if (this [I] = e) return I;} return-1;} // escape ht Ml tag function HtmlEncode (text) {return text. replace (// g ,'&'). replace (/\ "/g ,'"'). replace (// g, '>')} // format the date DateFormat ('yyyy _ MM_dd hh: mm: ss: SS w q ') function DateFormat (format, date) {if (! Date) {date = new Date ();} var Week = ['day', 'yi', '2', '3', '4', '5 ', '6']; var o = {"y +": date. getYear (), // year "M +": date. getMonth () + 1, // month "d +": date. getDate (), // day "h +": date. getHours (), // hour "H +": date. getHours (), // hour "m +": date. getMinutes (), // minute "s +": date. getSeconds (), // second "q +": Math. floor (date. getMonth () + 3)/3), // quarter "S": date. getMilliseconds (), // millisec Ond "w": Week [date. getDay ()]} if (/(y + )/. test (format) {format = format. replace (RegExp. $1, (date. getFullYear () + ""). substr (4-RegExp. $1. length);} for (var k in o) {if (new RegExp ("(" + k + ")"). test (format) {format = format. replace (RegExp. $1, RegExp. $1. length = 1? O [k]: ("00" + o [k]). substr ("" + o [k]). length) ;}} return format ;}// set the cookie value function setCookie (name, value, Hours) {var d = new Date (); var offset = 8; var utc = d. getTime () + (d. getTimezoneOffset () * 60000); var nd = utc + (3600000 * offset); var exp = new Date (nd); exp. setTime (exp. getTime () + Hours x 60*60*1000); document. cookie = name + "=" + escape (value) + "; path =/; expires =" + exp. to GMTString () + "; domain = 360doc.com;"} // obtain the cookie value function getCookie (name) {var arr = document. cookie. match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"); if (arr! = Null) return unescape (arr [2]); return null} // Add to favorites function AddFavorite (sURL, sTitle) {try {window. external. addFavorite (sURL, sTitle)} catch (e) {try {window. sidebar. addPanel (sTitle, sURL, "")} catch (e) {alert ("failed to add to favorites, please add with Ctrl + D ")}}} // set it to the homepage function setHomepage (homeurl) {if (document. all) {document. body. style. behavior = 'url (# default # homepage) '; document. body. setHomePage (homeurl)} el Se if (window. sidebar) {if (window. netscape) {try {netscape. security. privilegeManager. enablePrivilege ("UniversalXPConnect")} catch (e) {alert ("this operation is rejected by the browser. To enable this function, enter about: config in the address bar, then, set the item signed. applets. codebase_principal_support value: true ") ;}} var prefs = Components. classes ['@ mozilla.org/preferences-service%1'%.getservice (Components. interfaces. nsIPrefBranch); prefs. setCharPref ('browser. start Up. homepage ', homeurl) }}// cross-browser binding event function addEventSamp (obj, evt, fn) {if (! OTarget) {return;} if (obj. addEventListener) {obj. addEventListener (evt, fn, false);} else if (obj. attachEvent) {obj. attachEvent ('on' + evt, fn);} else {oTarget ["on" + sEvtType] = fn ;}// cross-browser deletion event function delEvt (obj, evt, fn) {if (! Obj) {return;} if (obj. addEventListener) {obj. addEventListener (evt, fn, false);} else if (oTarget. attachEvent) {obj. attachEvent ("on" + evt, fn);} else {obj ["on" + evt] = fn ;}// determine whether a mobile device accesses function isMobileUserAgent () {return (/iphone | ipod | android. * mobile | windows. * phone | blackberry. * mobile/I. test (window. navigator. userAgent. toLowerCase ();} // perfect judge whether it is the URL function IsURL (strUrl) {var regular =/^ \ B (https? | Ftp ):\/\/)? [-A-z0-9] + (\. [-a-z0-9] + )*\.(?: Com | edu | gov | int | mil | net | org | biz | info | name | museum | asia | coop | aero | [a-z] [a-z] | ((25 [0-5]) | (2 [0-4] \ d) | (1 \ d) | ([1-9] \ d) | \ d )) \ B (\/[-a-z0-9 _:\@&? = + ,.! \/~ % \ $] *)?) $/I if (regular. test (strUrl) {return true;} else {return false ;}// obtain the page height function getPageHeight () {var g = document, a = g. body, f = g.doc umentElement, d = g. compatMode = "BackCompat "? A: g.doc umentElement; return Math. max (f. scrollHeight,. scrollHeight, d. clientHeight);} // obtain the page Width function getPageWidth () {var g = document, a = g. body, f = g.doc umentElement, d = g. compatMode = "BackCompat "? A: g.doc umentElement; return Math. max (f. scrollWidth,. scrollWidth, d. clientWidth);} // obtain the visible width of the page function getPageViewWidth () {var d = document, a = d. compatMode = "BackCompat "? D. body: d.doc umentElement; return a. clientWidth;} // obtain the visual height of the page function getPageViewHeight () {var d = document, a = d. compatMode = "BackCompat "? D. body: d.doc umentElement; return. clientHeight;} // obtain the scrollLeftfunction getPageScrollLeft () {var a = document; return a.doc umentElement. scrollLeft |. body. scrollLeft;} // obtain the page scrollTopfunction getPageScrollTop () {var a = document; return a.doc umentElement. scrollTop |. body. scrollTop;} // obtain the width and height of the visible range of the Form. function getViewSize () {var de = document.doc umentElement; var db = document. body; var viewW = De. clientWidth = 0? Db. clientWidth: de. clientWidth; var viewH = de. clientHeight = 0? Db. clientHeight: de. clientHeight; return Array (viewW, viewH);} // random number timestamp function uniqueId () {var a = Math. random, B = parseInt; return Number (new Date ()). toString () + B (10 * a () + B (10 * a () + B (10 * ());} // obtain the location where the webpage is rolled. function getScrollXY () {return document. body. scrollTop? {X: document. body. scrollLeft, y: document. body. scrollTop }:{ x: document.doc umentElement. scrollLeft, y: document.doc umentElement. scrollTop }}// match the Chinese phone number (0511-4405222 or 021-87888822) function istell (str) {var result = str. match (/\ d {3}-\ d {8} | \ d {4}-\ d {7}/); if (result = null) return false; return true;} // ID card (15 or 18 digits) function isidcard (str) {var result = str. match (/\ d {15} | \ d {18}/); if (result = = Null) return false; return true;} // mobile phone function checkMobile (str) {if (! (/^ 1 [3 | 5 | 8] [0-9] \ d {4, 8} $ /. test (str) {return false;} return true;} // judge whether the input is a string consisting of 0-9/A-Z/a-z function isalphanumber (str) {var result = str. match (/^ [a-zA-Z0-9] + $/); if (result = null) return false; return true;} // determines whether the input is a valid Email function isemail (str) {var result = str. match (/^ \ w + (-\ w +) | (\. \ w +) * \ @ [A-Za-z0-9] + ((\. |-) [A-Za-z0-9] + )*\. [A-Za-z0-9] + $/); if (result = null) return false; r Eturn true;} // convert the amount in upper case to transform ('100%. 23 ') function transform (tranvalue) {try {var I = 1; var dw2 = new Array ("", "", ""); // large unit var dw1 = new Array ("pick up", "EMPTY", "EMPTY"); // small unit var dw = new Array ("zero", "one ", "II", "San", "Si", "Wu", "Lu", "Jun "); // The integer part is converted to uppercase in lower case and displayed in the total upper case text box // separate the integer and the decimal var source = splits (tranvalue ); var num = source [0]; var dig = source [1]; // convert the integer part var k1 = 0; // small unit va R k2 = 0; // large unit var sum = 0; var str = ""; var len = source [0]. length; // The length of the integer for (I = 1; I <= len; I ++) {var n = source [0]. charAt (len-I); // obtain the number var bn = 0 on a single digit; if (len-I-1> = 0) {bn = source [0]. charAt (len-I-1); // obtain the Number in the previous digit of a certain digit} sum = sum + Number (n); if (sum! = 0) {str = dw [Number (n)]. concat (str); // obtain the upper-case number corresponding to this number and insert it to the front of the str string if (n = '0') sum = 0 ;} if (len-I-1> = 0) {// if (k1! = 3) {// Add a small unit if (bn! = 0) {str = dw1 [k1]. concat (str);} k1 ++;} else {// no small unit added, increase unit k1 = 0; var temp = str. charAt (0); if (temp = "" | temp = "") // if no number exists before a large unit, remove str = str. substr (1, str. length-1); str = dw2 [k2]. concat (str); sum = 0 ;}} if (k1 = 3) {// small units to thousands of units into a k2 ++ ;}} // convert the fractional part var strdig = ""; if (dig! = "") {Var n = dig. charAt (0); if (n! = 0) {strdig + = dw [Number (n)] + ""; // Add a Number} var n = dig. charAt (1); if (n! = 0) {strdig + = dw [Number (n)] + "points"; // Add a Number} str + = "Yuan" + strdig;} catch (e) {return "0 RMB" ;}return str ;}// split the integer and Fractional function splits (tranvalue) {var value = new Array ('',''); temp = tranvalue. split (". "); for (var I = 0; I <temp. length; I ++) {value = temp;} return value;} // format the number function number_format (number, decimals, dec_point, thousands_sep) {/** parameter description: * number: number to be formatted * decimals: number of digits to be retained * Dec_point: decimal point * thousands_sep: kilobytes of characters **/number = (number + ''). replace (/[^ 0-9 +-Ee.] /g, ''); var n =! IsFinite (+ number )? 0: + number, prec =! IsFinite (+ decimals )? 0: Math. abs (decimals), sep = (typeof thousands_sep = 'undefined ')? ',': Thousands_sep, dec = (typeof dec_point = 'undefined ')? '. ': Dec_point, s = '', toFixedFix = function (n, prec) {var k = Math. pow (10, prec); return ''+ Math. ceil (n * k)/k;}; s = (prec? ToFixedFix (n, prec): ''+ Math. round (n). split ('.'); var re = /(-? \ D +) (\ d {3})/; while (re. test (s [0]) {s [0] = s [0]. replace (re, "$1" + sep + "$2");} if (s [1] | ''). length <prec) {s [1] = s [1] | ''; s [1] + = new Array (prec-s [1]. length + 1 ). join ('0');} return s. join (dec );}


 

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.