zoukankan      html  css  js  c++  java
  • JavaScript 常用方法总结

    1、手机类型判断

    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)),
    }

    2、返回字符串长度,汉子计数为2

    function strLength(str) {
    var a = 0;
    for (var i = 0; i < str.length; i++) {
      if (str.charCodeAt(i) > 255)
          a += 2;//按照预期计数增加2
      else
          a++;
    }
    return a;
    }

    3、

    function GetQueryStringRegExp(name,url) {
    var reg = new RegExp("(^|?|&)" + name + "=([^&]*)(s|&|$)", "i");
    if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/+/g, " ")); return "";
    
    
    } 

    4、js 绑定事件 适用于任何浏览器的元素绑定

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

    5、获得当前浏览器JS的版本

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

    6、获取当前点击事件的Object对象

    function getEvent() {
    if (document.all) {
       return window.event; //如果是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;
    }; 

    7、字符串截取方法

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

    8、JS 弹出新窗口全屏

    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_);
    //模拟form提交打开新页面
    var f = document.createElement("form");
    f.setAttribute('action', 'http://www.che168.com/pinggu/eva_' + msgResult.message[0] + '.html');
    f.target = '_blank';
    document.body.appendChild(f);
    f.submit(); 

    9、全选/全不选

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

    10、移除事件

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

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

    12、Ajax 请求 

     1 C.ajax = function (args) {
     2 var self = this;
     3 this.options = {
     4    type: 'GET',
     5    async: true,
     6    contentType: 'application/x-www-form-urlencoded',
     7    url: 'about:blank',
     8    data: null,
     9    success: {},
    10    error: {}
    11 };
    12 this.getXmlHttp = function () {
    13    var xmlHttp;
    14    try {
    15        xmlhttp = new XMLHttpRequest();
    16    }
    17    catch (e) {
    18        try {
    19            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    20        }
    21        catch (e) {
    22            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    23        }
    24    }
    25    if (!xmlhttp) {
    26        alert('您的浏览器不支持AJAX');
    27        return false;
    28    }
    29    return xmlhttp;
    30 };
    31 this.send = function () {
    32    C.each(self.options, function (key, val) {
    33        self.options[key] = (args[key] == null) ? val : args[key];
    34    });
    35 
    36    var xmlHttp = new self.getXmlHttp();
    37    if (self.options.type.toUpperCase() == 'GET') {
    38        xmlHttp.open(self.options.type, self.options.url + (self.options.data == null ? "" : ((/[?]$/.test(self.options.url) ? '&' : '?') + self.options.data)), self.options.async);
    39    }
    40    else {
    41        xmlHttp.open(self.options.type, self.options.url, self.options.async);
    42        xmlHttp.setRequestHeader('Content-Length', self.options.data.length);
    43    }
    44    xmlHttp.setRequestHeader('Content-Type', self.options.contentType);
    45    xmlHttp.onreadystatechange = function () {
    46        if (xmlHttp.readyState == 4) {
    47            if (xmlHttp.status == 200 || xmlHttp.status == 0) {
    48                if (typeof self.options.success == 'function') self.options.success(xmlHttp.responseText);
    49                xmlHttp = null;
    50            }
    51            else {
    52                if (typeof self.options.error == 'function') self.options.error('Server Status: ' + xmlHttp.status);
    53            }
    54        }
    55    };
    56 
    57    xmlHttp.send(self.options.type.toUpperCase() == 'POST' ? self.options.data.toString() : null);
    58 };
    59 this.send();
    60 };  
  • 相关阅读:
    (Good Bye 2019) Codeforces 1270B Interesting Subarray
    (Good Bye 2019) Codeforces 1270A Card Game
    Codeforces 1283D Christmas Trees(BFS)
    Codeforces 1283C Friends and Gifts
    Codeforces 1283B Candies Division
    1095 Cars on Campus (30)
    1080 Graduate Admission (30)
    1099 Build A Binary Search Tree (30)
    1018 Public Bike Management (30)
    1087 All Roads Lead to Rome (30)
  • 原文地址:https://www.cnblogs.com/zywaf/p/7193255.html
Copyright © 2011-2022 走看看