js 常用类

var JScriptLib = {
    /**
    *异步请求
    *rMethod 访问方式 get or post
    *POST方式可以发送4MB数据 GET方式只能发送256KB数据
    *请求带有参数用POST方式,POST方式将参数放置在页面的隐藏控件内
    *没有参数使用GET方式
    *对于请求的页面在中途可能发生更改的,也最好用POST方式,用GET方式可能会拿不到最新的信息
    *rAsync 是否为异步 true or false
    *rUrl 请求地址
    *rEncoding: application/x-www-form-urlencoded or application/json;charset=UTF-8
    *rParam 发送参数
    *callMethod 回调函数
    */
    ajax: function(rMethod, rAsync, rUrl, rEncoding, rParam, callMethod) {
        xmlHttp: NaN;
        //判断浏览器           
        if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //IE           
        } else if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest(); //非IE           
        } else {
            xmlHttp = NaN;
        }
        xmlHttp.open(rMethod, rUrl, rAsyn);
        xmlHttp.onreadystatechange = function() {
            //判断状态               
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                callMethod(xmlHttp.responseText);
            }
        }
        //定义传输的文件HTTP头信息
        xmlHttp.setRequestHeader("Content-Type", rEncoding); //采用的编码方式
        xmlHttp.send(rParam);
    },
    /**
    *获取document中elements对象 不考虑空格
    *obj document中elements标识 id name tagname(标签名称)
    *cmd 0 id 1 name 2 tagname
    *当0 返回唯一对象 当1、2 返回集合 否则返回FALSE
    */
    $: function(obj, cmd) {
        var temp;
        switch (cmd) {
            case 0: //id
                temp = document.getElementById(obj);
                break;
            case 1: //name
                temp = document.getElementsByName(obj);
                break;
            case 2: //tagname
                temp = document.getElementsByTagName(objtagname);
                break;
            default:
                temp = false;
                break;
        }
        return temp;
    },
    /**
    *字符串左右空格过滤
    *str 字符串
    *direct 0 全部 1 左边 2右边 3 左右两边
    *返回过滤后的字符串
    */
    trim: function(str, direct) {
        var temp = "";
        switch (direct) {
            case 0: //全部
                temp = str.replace(/\s+/g, "");
                break;
            case 1: //左边
                temp = str.replace(/(^\s*)/g, "");
                break;
            case 2: //右边
                temp = str.replace(/(\s*$)/g, "");
                break;
            case 3: //左右两边
                temp = str.replace(/(^\s*)|(\s*$)/g, "");
                break;
            default:
                temp = str;
                break;
        }
        return temp;
    },
    /**
    *判断是否为空 不考虑空格
    *str 对象任何类型
    */
    empty: function(str) {
        switch (typeof (str)) {
            case 'string':
                return str.length == 0 ? true : false;
                break;
            case 'number':
                return str == 0;
                break;
            case 'object':
                return str == null;
                break;
            case 'array':
                return str.length == 0;
                break;
            default:
                return true;
        }
    },
    /**
    *判断值是否是int
    *int true 否则FALSE
    */
    isInt: function(intvar) {
        if (intvar == "") {
            return false;
        }
        reg = /\D+/;
        return !reg.test(intvar);
    },
    /**
    *判断值是否是数据类型
    *number true 否则FALSE
    */
    isNumber: function(numval) {
        reg = /^[\d|\.|,]+$/;
        return reg.test(numval);
    },
    /**
    *判断值是否是时间类型
    *time true 否则FALSE
    */
    isTime: function(timeval) {
        reg = /^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}$/;
        return reg.test(timeval);
    },
    /**
    * 当前鼠标X座标
    */
    mouseX: function(e) {
        return Browser.isIE ? event.x + document.documentElement.scrollLeft - 2 : e.pageX;
    },
    /**
    *
    */
    request: function(url, item) {
        sValue = url.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
        return sValue ? sValue[1] : sValue;
    },
    /**
    *当前鼠标Y座标
    */
    mouseY: function(e) {
        return Browser.isIE ? event.y + document.documentElement.scrollTop - 2 : e.pageY;
    },
    /**
    *判断传入的两个值是否相等 不考虑空格
    *obj1、obj2 两个值 可以是任何类型的值
    *相等返回true 否则FALSE
    */
    equal: function(obj1, obj2) {
        return obj1 == obj2 ? true : false;
    },
    /**
    *格式验证 不考虑空格
    *str 要验证的字符串
    *验证选择 0邮箱 1手机号 2家庭电话 3邮编 4简单身份证
    *返回true 验证通过 FALSE验证失败
    */
    regularValidator: function(str, cmd) {
        reg = "";
        switch (cmd) {
            case 0: //邮箱
                reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
                break;
            case 1: //手机号
                reg = /^(13[0-9]{9})|(15[89][0-9]{8})$/
                break;
            case 2: //家庭电话
                reg = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
                break;
            case 3: //邮编
                reg = /^[1-9][0-9]{5}$/;
                break;
            case 4: //身份证
                reg = /^(\d{18,18}|\d{15,15}|\d{17,17}x)$/;
                break;
            default:
                return false;
        }
        return reg.test(str);
    },
    /**
    *验证身份证格式
    *str 要验证的身份证号
    *返回 字符串结果
    */
    validatorIdCard: function(str) {
        temp = "";
        idcard = str;
        Errors = new Array("验证通过!", "身份证号码位数不对!", "身份证号码出生日期超出范围或含有非法字符!",
       "身份证号码校验错误!", "身份证地区非法!");
        area = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海",
            32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东",
            45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海",
            64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
        }
        idcard, Y, JYM;
        S, M;
        idcard_array = new Array();
        idcard_array = idcard.split("");
        if (area[parseInt(idcard.substr(0, 2))] == null) temp = Errors[4];
        switch (idcard.length) {
            case 15:
                if ((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0)) {
                    ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2] [0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9])) [0-9]{3}$/; //测试出生日期的合法性
                } else {
                    ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2] [0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2] [0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/; //测试出生日期的合法性
                }
                if (ereg.test(idcard))
                    temp = Errors[0];
                else
                    temp = Errors[2];
                break;
            case 18:
                if (parseInt(idcard.substr(6, 4)) % 4 == 0 || (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard.substr(6, 4)) % 4 == 0)) {
                    ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2] [0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9])) [0-9]{3}[0-9Xx]$/; //闰年出生日期的合法性正则表达式
                } else {
                    ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2] [0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2] [0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/; //平年出生日期的合法性正则表达式
                }
                if (ereg.test(idcard)) {
                    S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7 + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9 +
     (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10 + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5 +
     (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8 + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4 +
     (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2 + parseInt(idcard_array[7]) * 1 + parseInt(idcard_array[8]) * 6 +
      parseInt(idcard_array[9]) * 3;
                    Y = S % 11;
                    M = "F";
                    JYM = "10X98765432";
                    M = JYM.substr(Y, 1);
                    if (M == idcard_array[17])
                        temp = Errors[0];
                    else
                        temp = Errors[3];
                } else
                    temp = Errors[2];
                break;
            default:
                temp = Errors[1];
                break;
        }
        return temp;
    },
    /**
    *编码
    */
    htmlEncode: function(str) {
        div = document.createElement("div");
        text = document.createTextNode(str);
        div.appendChild(text);
        return div.innerHTML;
    },
    /**
    *解码
    */
    htmlDecode: function(str) {
        div = document.createElement("div");
        div.innerHTML = str;
        return div.innerHTML;
    },
    /*
    *获取cookie
    *decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码
    */
    getCookie: function(check_name) {
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f
        for (i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split('=');


            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
                    cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                return cookie_value;
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if (!b_cookie_found) {
            return null;
        }
    },
    /*
    *设置cookie
    */
    setCookie: function(name, value, expires, path, domain, secure) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime(today.getTime());
        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
        if (expires) {
            expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date(today.getTime() + (expires));

        document.cookie = name + "=" + escape(value) +
        ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
        ((path) ? ";path=" + path : "") +
        ((domain) ? ";domain=" + domain : "") +
        ((secure) ? ";secure" : "");
    },
    /*
    *删除cookie
    */
    removeCookie: function(name, path, domain) {
        if (getCookie(name)) {
            document.cookie = name + "="
            + ((path) ? ";path=" + path : "")
            + ((domain) ? ";domain=" + domain : "")
            + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }
    },
    /*
    *获取元素起点
    */
    getPosition: function(o) {
        var t = o.offsetTop;
        var l = o.offsetLeft;
        while (o = o.offsetParent) {
            t += o.offsetTop;
            l += o.offsetLeft;
        }
        var pos = { top: t, left: l };
        return pos;
    },
    /*
    *处理整个HTML文档
    */
    cleanWhitespace1: function(element) {
        //如果不提供参数,则处理整个HTML文档
        element = element || document;
        //使用第一个子节点作为开始指针
        var cur = element.firstChild;
        //临时变量用来保存当前节点的下个节点
        var tmp;
        //一直到没有子节点为止
        while (cur != null) {
            //保存当前节点的下个节点
            tmp = cur.nextSibling
            //如果节点为文本节点,应且包含空格
            if (cur.nodeType == 3 && !/\S/.test(cur.nodeValue)) {
                //删除这个文本节点
                element.removeChild(cur);
                //否则,它就是一个元素
            } else if (cur.nodeType == 1) {
                //递归整个文档
                cleanWhitespace(cur);
            }
            cur = tmp; //遍历子节点
        }
    },
    /*
    *清除本节点的空白,不遍历子节点
    */
    cleanWhitespace: function(element) {
        var element = element;
        for (var i = 0; i < element.childNodes.length; i++) {
            var node = element.childNodes[i];
            if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
                element.removeChild(node);
        }
    } //,此处加 , 符号在ie中报错。但是在dreamweaver中没错
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章