项目中自定义写的一些方法


/**
 * Created by kk on 2017/2/7.
 */

/**
 * 1.验证码:
 */

    var codes;
    function createCode(n) {
        var checkCode = document.getElementsByClassName("imgCode")[0];
        var chars = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        var codes = "";
        for(var i = 0; i < n ; i ++) {
            var id = Math.floor(Math.random()*36);
            codes += chars[id];
        };
        return codes;
    };

/**
 * 2.保留n位小数&千分位(金钱):
 */

function comdify(s,n) {
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    t = "";
    for(i = 0; i < l.length; i ++ )
    {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
}

/**
 * 3.计算两个日期之间的时间差
 */

function getDateDiff(date1,date2){
    var arr1=date1.split('-');
    var arr2=date2.split('-');
    var d1=new Date(arr1[0],arr1[1],arr1[2]);
    var d2=new Date(arr2[0],arr2[1],arr2[2]);
    var sdDay = (d2.getTime()-d1.getTime())/(1000*3600*24);
    return sdDay
}

/**
 * 4.关闭页面(弹出):
 */

function CloseWebPage(){
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
            window.opener = null;
            window.close();
        } else {
            window.open('', '_top');
            window.top.close();
        };
    }else if (navigator.userAgent.indexOf("Firefox") > 0) {
        window.location.href = 'about:blank ';
    } else {
        window.opener = null;
        window.open('', '_self', '');
        window.close();
    };
};
//超出指定字数,显示省略号
function ellipsis(id,sNum){
    var sVal = id.text();
    var len = sVal.length;
    if(len>=sNum){
        var sText = sVal.substring(0,sNum-2);
        id.html(sText+" ..... ");
        id.css("textAlign","left")
    }
};

/**
 * 5.html中异步加载html文件:
 */

ajaxload("./xxx.html","#xxx");
function ajaxload(local,id){
    htmlobj=$.ajax({url:local,async:false});
    $(id).html(htmlobj.responseText);
}

/**
 * 6.参数转化上传后台:
 */

function ObjStory(id,biaoti,author){//声明对象
        this.ID = id;
        this.Biaoti= biaoti;
        this.Author= author;
}
document.getElementsByTagName("tr").length
var Array=[];
    for(var i=0;i<3;i++){
        var ip = i
        var is = 2*i;
        var io = 3*i
        Array.push(new ObjStory(i,is,io));
    }
var posts={list:JSON.stringify(Array)}//JSON.stringify(Array)数组转化json
$("button").click(function () {
    jsonAjax(posts);
})
function jsonAjax(json){
    $.ajax({
        url:url,
        type:"POST",
        data:json,
        success:function(data){
            console.log("11111");
        }
    })
};
/*
事件委托代理
 */
$(document).on("click","#shouyeNav",function (){
    // window.location = "/";
});

/*
图片上传本地预览
 */
function imageViews(inputfile,viewImg,imgClass,width,height){
    var inputfile = document.getElementById(inputfile);//file标签id
    var viewImg = document.getElementsByClassName(viewImg)[0];//预览图片DIV
    viewImg.innerHTML = "";
    var fileList = inputfile.files;
    for (var i = 0; i < fileList.length; i++){
        if(fileList[i].name.indexOf('.png') != -1||fileList[i].name.indexOf('.jpg') != -1||fileList[i].name.indexOf('.jpeg') != -1||ffileList[i].name.indexOf('.gif') != -1||fileList[i].name.indexOf('.bmp') != -1){
            viewImg.innerHTML += "<div style='float:left' class='imgPic'> <img class='"+ imgClass + "' style='cursor: pointer' /> </div>";//img的类名
            var imgObjPreview = document.getElementsByClassName(imgClass)[i];
            //console.log(viewImg)
            if (inputfile.files && inputfile.files[i]) {
                imgObjPreview.style.display = 'block';
                imgObjPreview.style.width = width+'px';
                imgObjPreview.style.height = height+'px';
                imgObjPreview.style.border = '1px solid #777';
                var imgurl = null;
                if (window.createObjectURL != undefined) {
                    imgurl = window.createObjectURL(inputfile.files[i])
                } else if (window.URL != undefined) {
                    imgurl = window.URL.createObjectURL(inputfile.files[i])
                } else if (window.webkitURL != undefined) {
                    imgurl = window.webkitURL.createObjectURL(inputfile.files[i])
                };
                imgObjPreview.src = imgurl;
            };
        }else{
            alert('选择文件错误,图片类型必须是,"gif", "jpeg", "jpg", "bmp", "png" 中的一种');
        };
    };
    return true;
};

//截取产品名称超过11个汉字的时候中间省略号
function cuts(a){
    var realLength = 0, len = a.length, charCode = -1;
    var m ;
    for (var i = 0; i < len; i++) {
        charCode = a.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) realLength += 1;
        else realLength += 2;
    }
    // str_cut = new String();
    var str1;
    var str2;
    if(realLength > 22){
        str1 = a.substr(a.length-4);
        str2 = a.substr(0,4);
        m = str2+"……"+str1
    }else{
        m = a;
    }
    return m;
}

//base64加密
// base64加密
function Base64() {

    // private property
    _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    // public method for encoding
    this.encode = function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = _utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
        }
        return output;
    }

    // public method for decoding
    this.decode = function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = _keyStr.indexOf(input.charAt(i++));
            enc2 = _keyStr.indexOf(input.charAt(i++));
            enc3 = _keyStr.indexOf(input.charAt(i++));
            enc4 = _keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = _utf8_decode(output);
        return output;
    }

    // private method for UTF-8 encoding
    _utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    };

    // private method for UTF-8 decoding
    _utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
var base64 = new Base64();
var entryid = base64.decode(window.location.href.split("?")[1].split("=@")[1]);//解密
base64.encode(entryid)//加密
//数组去重
function unique(arr) {
    var ret = []
    var hash = {}
    for (var i = 0; i < arr.length; i++) {
        var item = arr[i]
        var key = typeof(item) + item
        if (hash[key] !== 1) {
            ret.push(item)
            hash[key] = 1
        }
    }
    return ret
}

//检查role是否存在并且判断btn按钮的显示
var timeCheck = setTimeout(function () {
    setrole();
},1);

function setrole() {
    console.log("开始检查role")
    var roleid = $("body").attr("role");
    console.log(roleid);
    if(roleid == 8){//3 核心企业付款岗
        clearTimeout(timeCheck);
    }else if(roleid == 2){//2 核心企业审批岗
        clearTimeout(timeCheck);
    }else if(roleid == 7){//1 核心企业管理岗
        clearTimeout(timeCheck);
    }else if(roleid == 0){//借款人
        clearTimeout(timeCheck);
    }else if(!roleid){//不存在的时候
        setTimeout(function () {
            console.log(1)
            setrole();
        },1)
    }
}
//预加载\
// async: false,
// beforeSend: function () {
//     $("#preLoazd").show();
// },
// complete: function () {
//     $("#preLoazd").fadeOut(800)
// },
window.history.back();//点击返回
location.reload();//刷新页面

////查找存在数据并返回数组对象
function searchByIndexOf(keyWord, list){
    var len = list.length;
    var arr = [];
    for(var i=0;i<len;i++){
        //如果字符串中不包含目标字符会返回-1
        if(list[i].name.indexOf(keyWord)>=0){
            arr.push(list[i]);
        }
    }
    return arr;
}
// 阻止事件冒泡
event.stopPropagation()

jQuery $.grep()方法//用于数组元素过滤筛选

 


posted @ 2018-04-04 10:03  number26  阅读(208)  评论(0)    收藏  举报