记录下自己实战中所用到的实用的小函数,留备用
  1. 替换<>

function toTxt(str) {
    var RexStr = /\<|\>|\&/g;
    str = str.replace(RexStr, function(MatchStr) {
        switch (MatchStr) {
            case "<":
                return "";
                break;
            case ">":
                return "";
                break;case "&":
            return "";
            break;
            default:
                break;
        }
    });
    currentS = str;
    return str;
}
食用方法:
var words ="<哈哈哈>";
toTxt(words);
//结果 words= "哈哈哈"
  1. 判断字符串是否存在数组中

    • indexOf()
    function IsInArray(arr,val){
    
        var testStr=','+arr.join(",")+",";
    
        return testStr.indexOf(","+val+",")!=-1;
    
    }
##### 食用方法:
```
var arr=new Array(["b",2,"a",4,"test"]);  
IsInArray(arr,'test');
//判断 test 字符串是否存在于 arr 数组中,存在返回true 否则false,此处将返回true 
```
- 正则表达式

js 中判断某个元素是否存在于某个 js 数组中,相当于 PHP 语言中的 in_array 函数。

```
Array.prototype.in_array=function(e){
  var r=new RegExp(','+e+',');  
  return (r.test(','+this.join(this.S)+','));  
};  
```

**食用方法:**

```
var arr=new Array([‘b’,2,‘a‘,4]);    
arr.in_array('b');
//判断'b'字符是否存在于 arr 数组中,存在返回true 否则false,此处将返回true  
```
**注:此函数只对字符和数字有效**

- 遍历

```
Array.prototype.in_array = function (element) {  
  for (var i = 0; i < this.length; i++) {  
      if (this[i] == element) {  
          return true;  
        }  
    } return false;  
}  
```

**食用方法:**

```
var arr=new Array(["b",2,"a",4,"test"]);  

arr.in_array('test');
//判断 test 字符串是否存在于 arr 数组中,存在返回true 否则false,此处将返回true
```
  1. 接受文件大小的转换
function change(limit){
  var size = "";
  if(limit < 0.1 * 1024){                            //小于0.1KB,则转化成B
      size = limit.toFixed(2) + "B"
  }else if(limit < 0.1 * 1024 * 1024){            //小于0.1MB,则转化成KB
      size = (limit/1024).toFixed(2) + "KB"
  }else if(limit < 0.1 * 1024 * 1024 * 1024){        //小于0.1GB,则转化成MB
      size = (limit/(1024 * 1024)).toFixed(2) + "MB"
  }else{                                            //其他转化成GB
      size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB"
  }

  var sizeStr = size + "";                        //转成字符串
  var index = sizeStr.indexOf(".");                    //获取小数点处的索引
  var dou = sizeStr.substr(index + 1 ,2)            //获取小数点后两位的值
  if(dou == "00"){                                //判断后两位是否为00,如果是则删除00
      return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size;
}

食用方法:

var size = 1000kb;
change(size);
console.log(size)//size=1M
  1. 随机生成用户ID
/*
 *  生成随机用户编号
 */
var getRndId = function () {
    var nowtime = new Date(),
        today = Date.prototype.Format.call(nowtime, 'MMdd');
    var timestamp = (nowtime.getTime() - new Date(nowtime.getFullYear(), nowtime.getMonth(), nowtime.getDate()).getTime()).toString(36),
        length = timestamp.length,
        i = 0;
    while (i < 6 - length) {
        timestamp = '0' + timestamp;
        i++;
    };
    return '网页客户-' + today + '-' + timestamp.toUpperCase();
};

食用方法

 userName = getRndId();

//温馨提示需要配合Date.prototype.Format一起食用,也就是时间格式化

  1. 封装ajax(json/jsonp)getpost请求
/*  
 * jsonp get
 */
function getServer(isRobot, url, params, callback) {
    var timestamp = new Date().getTime();
    ext.ajax(isRobot ? robotUrl + url : hostUrl + url, {
        async: true,
        type: "get",
        cache: false,
        data: params,
        dataType: "jsonp",
        success: function (data) {
            // 成功结果
            callback(data);
        },
        error: function (err) {
            // 失败结果
            console.log(err);
        }
    })
}

食用方法

getServer(isRobot, url, param, callback);
/*
 *  post
 */
function postServer(isRobot, url, params, callback) {
    ext.ajax(isRobot ? robotUrl + url : hostUrl + url, {
        // async: false,
        type: "post",
        // cache: false,
        data: params,
        dataType: "json",
        success: function (data) {
            callback(data);
        },
        error: function (err) {
            console.log(err);
        }
    })
}

食用方法

postServer(isRobot, url, param, callback);
  1. javascript加载js
function loadJs(src, success, error) {
    var script = document.createElement("script"),
        body = document.getElementsByTagName("body")[0],
        isload = false;
    var charset = document.characterSet || document.charset;
    script.type = "text/javascript";
    script.src = src;
    script.charset=charset;
    script.onreadystatechange = function () {
        var r = script.readyState;
        if (!isload && (r === 'loaded' || r === 'complete')) {
            isload = true;
            success && success();
            script.onreadystatechange = null;
            body.removeChild(script);
        }
    }
    script.onload = function () {
        if (!isload) {
            isload = true;
            success && success();
            body.removeChild(script);
        }
    }
    if (error) {
        script.onerror = error;
    }
    body.appendChild(script);
}

食用方法

var sdkUrl = options.sourcePrefix + 'QiZhiSDK(3).js';
loadJs(sdkUrl, function () {
    }, function () {
        console.log(sdkUrl + '加载失败');
},charset)
/*
 *  加载js
 */
function insertJS(src) {
    var ohead = document.getElementsByTagName('head').item(0);
    var oscript = document.createElement("script");
    console.log(oscript);
    oscript.type = "text/javascript";
    oscript.src = src;
    ohead.appendChild(oscript);
}

/*
 *  加载css
 */
function insertCSS(src) {
    var ohead = document.getElementsByTagName('head').item(0);
    var olink = document.createElement("link");
    olink.rel = 'stylesheet';
    olink.href = src;
    ohead.appendChild(olink);
}
function initSource(options) {
    // 加载voice
    var audioEle = document.createElement('audio');
    audioEle.preload = 'preload';
    audioEle.src = options.sourcePrefix + 'css/voice.mp3';
    audioEle.id = 'smartnlp-tipVoice';
    document.getElementsByTagName('body')[0].appendChild(audioEle);
    // 加载css
    insertCSS(options.sourcePrefix + 'css/qz-chatframe.css');

}
/*
 *  阻止冒泡
 */
function stopBubble(e) {
    if (e && e.stopPropagation)
        e.stopPropagation();
    else
        window.event.cancelBubble = true;
}
/*
 *  阻止默认事件
 */
function stopDefault(e) {
    if (e && e.preventDefault)
        e.preventDefault();
    else
        window.event.returnValue = false;
    return false;
}
/*
 *  判断是否是移动端
 */
function isMobile() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
        return true;
    } else {
        return false;
    }
}
/*
 *  微信ajax处理
 */
var xmlHttpRequest;

ext(function () {

    if (window.XMLHttpRequest) {

        xmlHttpRequest = new XMLHttpRequest();

    } else {

        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");

    }

    xmlHttpRequest.open("GET", "AjaxServlet", true);

});
/*
 *  扩展jquery.cookie
 */
function jqCookie(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].replace(/(^[ ]+)|([ ]+$)/ig, '');
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 *  获取css样式
 */
var getCss = function (o, key) {
    return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, false)[key];
};
/*
 *  拖拽函数
 */
var params = {
    left: 0,
    top: 0,
    currentX: 0,
    currentY: 0,
    flag: false
};
/*
 *  拖拽具体实现
 */
var startDrag = function (bar, target, callback) {
    if (getCss(target, "left") !== "auto") {
        params.left = getCss(target, "left");
    }
    if (getCss(target, "top") !== "auto") {
        params.top = getCss(target, "top");
    }
    //o是移动对象
    params.xMax = document.documentElement.clientWidth - target.clientWidth;
    params.yMax = document.documentElement.clientHeight - target.clientHeight;
    params.xMin = 0;
    params.yMin = 0;
    bar.onmousedown = function (event) {
        params.flag = true;
        if (!event) {
            event = window.event;
            //防止IE文字选中
            bar.onselectstart = function () {
                return false;
            }
        }
        var e = event;
        params.currentX = e.clientX;
        params.currentY = e.clientY;
    };
    document.onmouseup = function () {
        params.flag = false;
        if (getCss(target, "left") !== "auto") {
            params.left = getCss(target, "left");
        }
        if (getCss(target, "top") !== "auto") {
            params.top = getCss(target, "top");
        }
    };
    document.onmousemove = function (event) {
        params.xMax = document.documentElement.clientWidth - target.clientWidth;
        params.yMax = document.documentElement.clientHeight - target.clientHeight;
        var e = event ? event : window.event;
        if (params.flag) {
            var nowX = e.clientX,
                nowY = e.clientY;
            var disX = nowX - params.currentX,
                disY = nowY - params.currentY;
            var targetX = parseInt(params.left) + disX,
                targetY = parseInt(params.top) + disY;
            target.style.left = moveDis(targetX, params.xMin, params.xMax) + "px";
            target.style.top = moveDis(targetY, params.yMin, params.yMax) + "px";
            if (event && event.preventDefault) {
                event.preventDefault();
            } else {
                window.event.returnValue = false;
            }
            return false;
        }
        if (typeof callback == "function") {
            callback(parseInt(params.left) + disX, parseInt(params.top) + disY);
        }
    }
    // 判断移动的距离
    function moveDis(target, min, max) {
        if (target > max) {
            return max;
        } else if (target < min) {
            return min;
        } else {
            return target;
        }
    }
};
/*
 *  获取滚动位置
 */
function getScrollTop() {
    var scrollTop = 0;
    if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop;
    } else if (document.body) {
        scrollTop = document.body.scrollTop;
    }
    return scrollTop;
}
/*
 *  时间格式化
 */
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
 /*
     *  引入css样式
     */
    function addNewStyle(newStyle) {
        if (ieFlag) {
            // ie8
            var str = newStyle;
            var node = document.createElement('style');
            node.type = 'text/css';
            if (node.styleSheet) { //ie下
                node.styleSheet.cssText = str;
            } else {
                node.innerHTML = str; //或者写成 nod.appendChild(document.createTextNode(str))
            }
            document.getElementsByTagName('head')[0].appendChild(node);
        } else {
            var styleElement = document.getElementById('styles_js');
            if (!styleElement) {
                styleElement = document.createElement('style');
                styleElement.type = 'text/css';
                styleElement.id = 'styles_js';
                document.getElementsByTagName('head')[0].appendChild(styleElement);
            }
            styleElement.appendChild(document.createTextNode(newStyle));
        }
    }

最后

如果该篇文章对你有效,请点下赞助/打赏支持哈~
您的支持是我最大的动力~


扫描二维码,在手机上阅读!