JavaScript common methods

mobile phone type judgment
var ua = navigator.userAgent.toLowerCase(),
      BrowserInfo = {    
    // android
    isAndroid: Boolean (ua.match (/android/g)),
   // iphone phone
    isIphone: Boolean (ua.match (/ iphone | ipod / g)),
   // ipad
    isIpad: Boolean(ua.match(/ipad/g)),
   // WeChat
    isWeixin: Boolean(ua.match(/MicroMessenger/g)),
}



Returns the length of the string, 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 the count by 2 as expected
    else
        a++;
    }
    return a;
 }


Get the parameters in the url
    /**
     * public method definition
     * @example: http://xxx.com/a.do?name=zhangsan
     * Output: getParameter('name') // 'zhangsan'
     */
    var getParameter = function(param, url) {
        var reg = new RegExp('[&,?,&]' + param + '=([^\\&]*)', 'i'),
              value = reg.exec(decodeURIComponent(decodeURIComponent(url || location.search || location.hash)));
        return value ? value[1] : '';
    }


js binding events for element bindings for any browser
function eventBind(obj, eventType, callBack) {
   // w3c
    if (obj.addEventListener) {
        obj.addEventListener(eventType, callBack, false);
    // low version ie
    }else if (window.attachEvent) {
        obj.attachEvent('on' + eventType, callBack);
    }else {
        obj['on' + eventType] = callBack;
    }
};
eventBind(document, 'click', bodyClick);


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;
    }
}


Get the Object object of the current click event
function getEvent() {    
    if (document.all) {        
    return window.event; //if it is 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 interception method
var 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 to judge whether the browser

judges whether it is an IE browser
if (document.all || !!window.ActiveXObject){
    alert("IE browser");
}else{
    alert("Non-IE browser");
}


Judgment is IE
var isIE = !! window.ActiveXObject;
var isIE6=isIE&&!window.XMLHttpRequest;
var isIE8 = isIE && !! document.documentMode;
var isIE7=isIE&&!isIE6&&!isIE8;
if (isIE){
    if (isIE6){
        alert(”ie6″);
    }else if (isIE8){
        alert(”ie8″);
    }else if (isIE7){
        alert(”ie7″);
    }
}

Judge the browser
function getOs() {   
    var ua = navigator.userAgent;
    if (ua.indexOf("MSIE 8.0") > 0) {        
        return "MSIE8";
    }else if (ua.indexOf("MSIE 6.0") > 0) {
        return "MSIE6";
    }else if (ua.indexOf("MSIE 7.0") > 0) {
        return "MSIE7";
    }else if (isFirefox = ua.indexOf("Firefox") > 0) {
        return "Firefox";
    }
    if (ua.indexOf("Chrome") > 0) {
        return "Chrome";
    }else {
        return "Other";
    }
}


JS judges the size of two dates
//Get the date value and convert it to date format
//replace(/\-/g, "\/") is to convert the date into a long date format according to the validation expression
// This is a good judgment to make a judgment
function ValidateDate(beginDate,endDate) {
    if (beginDate.length > 0 && endDate.length>0) {
        var sDate = new Date(beginDate.replace(/\-/g, "\/"));                
        var eDate= new Date(endDate.replace(/\-/g, "\/"));                
        if (sDate > eDate) {
            // start date is less than end date
            return false;
        }
        return true;
    }
}

Enter to submit
document.getElementById("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) {
        // submit operation
    }
}


JS 写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 cookies
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
var 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.options.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('');
};


JS replaces illegal characters mainly for special characters that appear in password authentication
function URLencode(sStr) {
     return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
};


Press Ctrl + Entert to submit the form directly
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();
        }
};


Js remove spaces 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, "");
    }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326618848&siteId=291194637