This article introduces common JavaScript methods to summarize the commonly used JS methods. Write them down today so that you can query them later.
/* Mobile Phone type judgment */var BrowserInfo = {userAgent: navigator. userAgent. toLowerCase () isAndroid: Boolean (navigator. userAgent. match (/android/ig), isIphone: Boolean (navigator. userAgent. match (/iphone | ipod/ig), isIpad: Boolean (navigator. userAgent. match (/ipad/ig), isWeixin: Boolean (navigator. userAgent. match (/MicroMessenger/ig )),}
/* Returns the string length. The man count is 2 */
Function strLength (str) {var a = 0; for (var I = 0; I <str. length; I ++) {if (str. charCodeAt (I)> 255) a + = 2; // increase by 2 elsea ++ as expected;} return ;}
Obtain parameters in a url
function GetQueryStringRegExp(name,url) {var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/\+/g, " ")); return "";}
/* Js binding event applies to Element Binding of any browser */
function eventBind(obj, eventType, callBack) {if (obj.addEventListener) {obj.addEventListener(eventType, callBack, false);}else if (window.attachEvent) {obj.attachEvent('on' + eventType, callBack);}else {obj['on' + eventType] = callBack;}};eventBind(document, 'click', bodyClick);
/* Obtain the current browser JS version */
function getjsversion(){var n = navigator;var u = n.userAgent;var apn = n.appName;var v = n.appVersion;var ie = v.indexOf('MSIE ');if (ie > 0){apv = parseInt(i = v.substring(ie + 5));if (apv > 3) {apv = parseFloat(i);}} else {apv = parseFloat(v);}var isie = (apn == 'Microsoft Internet Explorer');var ismac = (u.indexOf('Mac') >= 0);var javascriptVersion = "1.0";if (String && String.prototype) {javascriptVersion = '1.1';if (javascriptVersion.match) {javascriptVersion = '1.2';var tm = new Date;if (tm.setUTCDate) {javascriptVersion = '1.3';if (isie && ismac && apv >= 5) javascriptVersion = '1.4';var pn = 0;if (pn.toPrecision) {javascriptVersion = '1.5';a = new Array;if (a.forEach) {javascriptVersion = '1.6';i = 0;o = new Object;tcf = new Function('o', 'var e,i=0;try{i=new Iterator(o)}catch(e){}return i');i = tcf(o);if (i && i.next) {javascriptVersion = '1.7';}}}}}}return javascriptVersion;}
/* Get the Object of the current Click Event */
Function getEvent () {if (document. all) {return window. event; // for ie} func = getEvent. caller; while (func! = Null) {var arg0 = func. arguments [0]; if (arg0) {if (arg0.constructor = Event | arg0.constructor = MouseEvent) | (typeof (arg0) = "object" & arg0.preventDefault & arg0.stopPropagation) {return arg0 ;}} func = func. caller;} return null ;};
/* String truncation method */
getCharactersLen: function (charStr, cutCount) {if (charStr == null || charStr == '') return '';var totalCount = 0;var newStr = '';for (var i = 0; i < charStr.length; i++) {var c = charStr.charCodeAt(i);if (c < 255 && c > 0) {totalCount++;} else {totalCount += 2;}if (totalCount >= cutCount) {newStr += charStr.charAt(i);break;}else {newStr += charStr.charAt(i);}}return newStr;}
/* JS pop-up window full screen */
Var tmp = window. open ("about: blank", "", "fullscreen = 1") tmp. moveTo (0, 0); tmp. resizeTo (screen. width + 20, screen. height); tmp. focus (); tmp. location. href = 'HTTP: // www.che168.com/pinggu/eva_' + msgResult. message [0] + '.html '; var config _ = "left = 0, top = 0, width =" + (window. screen. width) + ", height =" + (window. screen. height); window. open ('HTTP: // www.che168.com/pinggu/eva_' + msgResult. message [0] + '.html ', "winHanle", config _); // simulate form submission to open the new page var f = document. createElement ("form"); f. setAttribute ('action', 'HTTP: // www.che168.com/pinggu/eva_' + msgResult. message [0] + '.html'invalid f.tar get = '_ blank'; document. body. appendChild (f); f. submit ();
/* Select all/select none */
function selectAll(objSelect) {if (objSelect.checked == true) {$("input[name='chkId']").attr("checked", true);$("input[name='chkAll']").attr("checked", true);}else if (objSelect.checked == false) {$("input[name='chkId']").attr("checked", false);$("input[name='chkAll']").attr("checked", false);}}
/* Determine the browser by js */
Determine whether it is an IE browser if (document. all) {alert ("IE browser");} else {alert ("non-IE browser");} if (!! Window. ActiveXObject) {alert ("IE browser");} else {alert ("non-IE browser");} judge how many var isIE is IE = !! Window. ActiveXObject; var isIE6 = isIE &&! Window. XMLHttpRequest; var isIE8 = isIE &&!! Document.doc umentMode; var isIE7 = isIE &&! IsIE6 &&! IsIE8; if (isIE) {if (isIE6) {alert ("ie6");} else if (isIE8) {alert ("ie8");} else if (isIE7) {alert ("ie7 ″);}}
/* Determine the browser */
function getOs() {if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {return "MSIE8";}else if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {return "MSIE6";}else if (navigator.userAgent.indexOf("MSIE 7.0") > 0) {return "MSIE7";}else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {return "Firefox";}if (navigator.userAgent.indexOf("Chrome") > 0) {return "Chrome";}else {return "Other";}}
/* JS determines that the two date formats are suitable for comparison between 2012-09-09 and 2012-9-9 */
// Get the date value and convert it to the date format. replace (/\-/g, "\/") converts the date to the Growth date format based on the validation expression, in this case, the function ValidateDate () {var beginDate = $ ("# t_datestart") is judged "). val (); var endDate = $ ("# t_dateend "). val (); if (beginDate. length> 0 & endDate. length> 0) {var sDate = new Date (beginDate. replace (/\-/g, "\/"); var eDate = new Date (endDate. replace (/\-/g, "\/"); if (sDate> eDate) {alert ('start date must be earlier than end date'); return false ;}}}
/* Remove event */
this.moveBind = function (objId, eventType, callBack) {var obj = document.getElementById(objId);if (obj.removeEventListener) {obj.removeEventListener(eventType, callBack, false);}else if (window.detachEvent) {obj.detachEvent('on' + eventType, callBack);}else {obj['on' + eventType] = null;}}
/* Press enter to submit */
$("id").onkeypress = function (event) {event = (event) ? event : ((window.event) ? window.event : "")keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode);if (keyCode == 13) {$("SubmitLogin").onclick();}}
/* JS execution timer */
timeStart = new Date().getTime();timesEnd = new Date().getTime();document.getElementById("time").innerHTML = timesEnd - timeStart;
/* JS write Cookie */
function setCookie(name, value, expires, path, domain) {if (!expires) expires = -1;if (!path) path = "/";var d = "" + name + "=" + value;var e;if (expires < 0) {e = "";}else if (expires == 0) {var f = new Date(1970, 1, 1);e = ";expires=" + f.toUTCString();}else {var now = new Date();var f = new Date(now.getTime() + expires * 1000);e = ";expires=" + f.toUTCString();}var dm;if (!domain) {dm = "";}else {dm = ";domain=" + domain;}document.cookie = name + "=" + value + ";path=" + path + e + dm;};
/* JS read Cookie */
function readCookie(name) {var nameEQ = name + "=";var ca = document.cookie.split(';');for (var i = 0; i < ca.length; i++) {var c = ca[i];while (c.charAt(0) == ' ') c = c.substring(1, c.length);if (c.indexOf(nameEQ) == 0) {return decodeURIComponent(c.substring(nameEQ.length, c.length))}} return null}
/* Ajax Request */
C. ajax = function (args) {var self = this; this. options = {type: 'get', async: true, contentType: 'application/x-www-form-urlencoded', url: 'about: blank ', data: null, success :{}, error :{}}; this. getXmlHttp = function () {var xmlHttp; try {xmlhttp = new XMLHttpRequest ();} catch (e) {try {xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP ");} catch (e) {xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ") ;}} if (! Xmlhttp) {alert ('your browser does not support AJAX '); return false;} return xmlhttp;}; this. send = function () {C. each (self. options, function (key, val) {self. options [key] = (args [key] = null )? Val: args [key] ;}); var xmlHttp = new self. getXmlHttp (); if (self. options. type. toUpperCase () = 'get') {xmlHttp. open (self. options. type, self. options. url + (self. options. data = null? "": (/[?] $/. Test (self. options. url )? '&':'? ') + Self. options. data), self. options. async);} else {xmlHttp. open (self. options. type, self. options. url, self. options. async); xmlHttp. setRequestHeader ('content-length', self. options. data. length);} xmlHttp. setRequestHeader ('content-type', self. options. contentType); xmlHttp. onreadystatechange = function () {if (xmlHttp. readyState = 4) {if (xmlHttp. status = 200 | xmlHttp. status = 0) {if (typeof self. op Tions. success = 'function') self. options. success (xmlHttp. responseText); xmlHttp = null;} else {if (typeof self. options. error = 'function') self. options. error ('server Status: '+ xmlHttp. status) ;}}; xmlHttp. send (self. options. type. toUpperCase () = 'post '? Self. options. data. toString (): null) ;}; this. send ();};
/* JS StringBuilder usage */
function StringBuilder() {this.strings = new Array;};StringBuilder.prototype.append = function (str) {this.strings.push(str);};StringBuilder.prototype.toString = function () {return this.strings.join('');};
/* Load JS to the top of LoadJS */
Function loadJS (url, fn) {var ss = document. getElementsByName ('script'), loaded = false; for (var I = 0, len = ss. length; I <len; I ++) {if (ss [I]. src & ss [I]. getAttribute ('src') = url) {loaded = true; break ;}} if (loaded) {if (fn & typeof fn! = 'Undefined' & fn instanceof Function) fn (); return false;} var s = document. createElement ('script'), B = false; s. setAttribute ('type', 'text/javascript '); s. setAttribute ('src', url); s. onload = s. onreadystatechange = function () {if (! B &&(! This. readyState | this. readyState = 'loaded' | this. readyState = 'complete') {B = true; if (fn & typeof fn! = 'Undefined' & fn instanceof Function) fn () ;}}; document. getElementsByTagName ('head') [0]. appendChild (s) ;}, bind: function (objId, eventType, callBack) {// applicable to binding var obj = document in any browser. getElementById (objId); if (obj. addEventListener) {obj. addEventListener (eventType, callBack, false);} else if (window. attachEvent) {obj. attachEvent ('on' + eventType, callBack);} else {obj ['on' + eventType] = callBack ;}} f Unction JSLoad (args) {s = document. createElement ("script"); s. setAttribute ("type", "text/javascript"); s. setAttribute ("src", args. url); s. onload = s. onreadystatechange = function () {if (! S. readyState | s. readyState = "loaded" | s. readyState = "complete") {if (typeof args. callback = "function") args. callback (this, args); s. onload = s. onreadystatechange = null; try {s. parentNode & s. parentNode. removeChild (s) ;}catch (e) {}}; document. getElementsByTagName ("head") [0]. appendChild (s );}
/* Clear the js reference loaded by LoadJS to the top */
function ClearHeadJs (src) {var js = document.getElementsByTagName('head')[0].children;var obj = null;for (var i = 0; i < js.length; i++) {if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {obj = js[i];}}document.getElementsByTagName('head')[0].removeChild(obj);};
/* Replacement of invalid characters in JS is mainly used for special characters in password verification */
function URLencode(sStr) {return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');};
/* Press Ctrl + Entert to directly submit the form */
document.body.onkeydown = function (evt) {evt = evt ? evt : (window.event ? window.event : null);if (13 == evt.keyCode && evt.ctrlKey) {evt.returnValue = false;evt.cancel = true;PostData();}};
/* Get the current time */
function GetCurrentDate() {var d = new Date();var y = d.getYear()+1900;month = add_zero(d.getMonth() + 1),days = add_zero(d.getDate()),hours = add_zero(d.getHours());minutes = add_zero(d.getMinutes()),seconds = add_zero(d.getSeconds());var str = y + '-' + month + '-' + days + ' ' + hours + ':' + minutes + ':' + seconds;return str;};function add_zero(temp) {if (temp < 10) return "0" + temp;else return temp;}
/* Js space removal method :*/
String.prototype.Trim = function(){ return this.replace(/(^\s*)|(\s*$)/g, ""); }String.prototype.LTrim = function(){return this.replace(/(^\s*)/g, "");}String.prototype.RTrim = function(){return this.replace(/(\s*$)/g, "");}
/* Js dynamically removes js references from the head */
this.ClearHeadJs = function (src) {var js = document.getElementsByTagName('head')[0].children;var obj = null;for (var i = 0; i < js.length; i++) {if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {obj = js[i];}}document.getElementsByTagName('head')[0].removeChild(obj);};
/* Add the entire UL click event to The onclick in UL */
function CreateFrom(url, params) {var f = document.createElement("form");f.setAttribute("action", url);for (var i = 0; i < params.length; i++) {var input = document.createElement("input");input.setAttribute("type", "hidden");input.setAttribute("name", params[i].paramName);input.setAttribute("value", params[i].paramValue);f.appendChild(input);}f.target = "_blank";document.body.appendChild(f);f.submit();};
/* Determine the JS version used by the browser */