一些JS常用的方法

/**

 * JS公用类库文件

 */

 

(function(){

    Tools = {

        W: window,

        D: document,

        Postfix: ".php",

        GetId: function(id){return document.getElementById(id)},

        hi:function(){alert(‘Hi‘)},

 

        /**

         * 验证类

         */

        Check: {

            /**

             * 验证表单输入框的值是否与指定值相符

             * @param name 要验证的输入框的name

             * @param value 要验证的值

             * @param message 验证失败时弹出的消息提示

             * @returns {boolean} 若与给定值相等,则返回true,不相等则返回false

             */

            input: function(name,value){

                var input = $(":input[name=‘"+name+"‘]");

                if(input.val() == value){

                    input.focus();

                    return true;

                }

                return false;

            },

 

            /**

             * 验证输入框的值是否为手机号码的格式

             * @param name 要验证的输入框的name

             * @returns {boolean} 若不符合格式要求返回true,否则返回false

             */

            phone: function(name){

                /*

                 * 联通号段:130/131/132/155/156/185/186/145/176;

                 * 电信号段:133/153/180/181/189/177;

                 * 移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178

                 */

                var reg = /^1(30|31|32|55|56|85|86|45|76|33|53|80|81|89|77|34|35|36|37|38|39|50|51|52|57|58|59|82|83|84|87|88|47|78)[0-9]{8}$/;

                var input = $(":input[name=‘"+name+"‘]");

                if(!reg.test(input.val())){

                    input.focus();

                    return true;

                }

                return false;

            },

 

            /**

             * 验证输入框的值是否为邮箱格式

             * @param name 要验证的输入框的name

             * @returns {boolean} 若不符合格式要求返回true,否则返回false

             */

            email: function(name){

                var reg = /^[a-zA-Z0-9_][email protected][a-z0-9]+\.[a-z]+$/;

                var input = $(":input[name=‘"+name+"‘]");

                if(!reg.test(input.val())){

                    input.focus();

                    return true;

                }

                return false;

            },

 

            /**

             * 验证输入框的值是否符合用户名的格式要求

             * @param name ~

             * @returns {boolean} ~

             */

            username: function(name){

                var reg = /^[a-zA-Z][a-zA-z0-9]{4,15}$/;

                var input = $(":input[name=‘"+name+"‘]");

                if(!reg.test(input.val())){

                    input.focus();

                    return true;

                }

                return false;

            },

 

            /**

             * 验证输入框的值是否符合密码格式要求

             * 格式要求:不能为纯数字,不能为纯字符,不能为纯标点符号,不能小于6位,不能大于18位

             * @param name ~

             * @returns {boolean} ~

             */

            password: function(name){

                var reg = /^([A-Z]+)$|^([a-z]+)$|^([0-9]+)$|^([-`=\\\[\];‘,\.\/[email protected]#\$%\^&\*\(\)_+\|\{}:"<>\?]+)$|^.{0,6}$|^.{18,}$/

                var input = $(":input[name=‘"+name+"‘]");

                if(reg.test(input.val())){

                    input.focus();

                    return true;

                }else{

                    return false;

                }

            },

 

            /**

             * 验证输入框的值是否符合身份证格式要求

             * @param name ~

             * @returns {boolean} ~

             */

            identification: function(name){

                var city={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:"国外 "};

                var input = $(":input[name=‘" + name + "‘]");

                var code = Ident.val();

 

                if(!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)){

                    input.focus();

                    return true;

                }

 

                else if(!city[code.substr(0,2)]){

                    input.focus();

                    return true;

                }

                else{

                    //18位身份证需要验证最后一位校验位

                    if(code.length == 18){

                        code = code.split(‘‘);

                        //∑(ai×Wi)(mod 11)

                        //加权因子

                        var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];

                        //校验位

                        var parity = [ 1, 0, ‘X‘, 9, 8, 7, 6, 5, 4, 3, 2 ];

                        var sum = 0;

                        var ai = 0;

                        var wi = 0;

                        for (var i = 0; i < 17; i++)

                        {

                            ai = code[i];

                            wi = factor[i];

                            sum += ai * wi;

                        }

                        var last = parity[sum % 11];

                        if(parity[sum % 11] != code[17]){

                            input.focus();

                            return true;

                        }

                    }

                }

                return false;

            }

        },

 

        /**

         * 用户中心类

         */

        Member: {

 

            /**

             * 登录方法

             * @param username 用户名输入框的name

             * @param password 密码输入框的name

             * @param requestURL 验证地址

             * @param locationURL 通过后的跳转地址

             * @returns {boolean}

             */

            login: function(username, password, requestURL, locationURL){

                var usernameInput = $(":input[name=‘" + username + "‘]");

                var passwordInput = $(":input[name=‘" + password + "‘]");

                if(Tools.Check.username(username)){

                    alert("用户名格式不符合要求");

                    return false;

                }

                if(Tools.Check.password(password)){

                    return false;

                }

                $.ajax({

                    url:requestURL,

                    type:"POST",

                    data:{

                        request:"Login",

                        username:usernameInput.val(),

                        password:passwordInput.val()

                    },

                    dataType:"json",

                    success:function(data){

                        if(data.state != 200){

                            alert(data.message);

                            return false;

                        }else{

                            location.href= locationURL;

                        }

                    }

                });

            },

            logout:function(URL){

                location.href = URL;

            }

        },

 

        Public: {

 

            /**

             * 复选框全选/反选方法

             * @param className 每组复选框的className

             * @param action 全选或反选操作,值为真则全选,值为假则反选

             */

            boxAllSel: function(className,action){

                var boxList = $(":input[type=‘checkbox‘]." + className);

                if(action){

                    for(var I in boxList){

                        boxList[I].checked = true;

                    }

                }else{

                    for(var I in boxList){

                        boxList[I].checked = boxList[I].checked ? false : true;

                    }

                }

            },

 

            /**

             * 批量请求方法,使用方法:

             * 将下拉菜单option的值设置为此种格式:请求地址:请求标识:弹出提示的消息内容:是否接收输入:接收输入时显示的消息:接收输入时的默认值

             * 请求地址:要发送到的URL地址,注意不要加后缀名。如action.php只需写action即可,后缀名在Tools中统一设置

             * 请求标识:本次请求发送的处理标识信息

             * 是否接收输入:true or false

             * @param o 操作列表的对象,如果直接在select对象上调用,传入this即可

             * @param className 复选框组的className

             */

            requests: function(o,className){

                //批量请求

                //url.request.message.input.inputMessage.inputValue

                var data = $("."+ className +":checked").serialize();

                if(data == ‘‘){

                    alert("您没有选中任何项");

                    o.value = o.options[0].value;

                    return;

                }

                var tempArr = O.value.split(‘.‘);

                if(!tempArr[0] || !tempArr[1]){

                    //验证URL及动作

                    alert("错误:缺少必须参数");

                    o.value = o.options[0].value;

                    return;

                }

                data += "&request=" + tempArr[1];

                var message = "确认删除选中项吗?";

                if(tempArr[2]){

                    //验证并设置提示消息

                    message = tempArr[2];

                }

                if(confirm(message)){

                    var input = false;

                    if(tempArr[3]){

                        //验证并设置是否接收用户输入

                        input = true;

                    }

                    if(input == ‘True‘){

                        var inputVal = prompt(tempArr[4],tempArr[5]);

                        data += "&input=" + inputVal;

                    }

                    $.ajax({

                        url:"./"+tempArr[0] + Tools.Postfix,

                        type:‘GET‘,

                        data:data,

                        dataType:‘json‘,

                        async:false,

                        success:function(data){

                            alert(data.message);

                            location.reload(true);

                        }

                    });

                }

            },

 

            /**

             * 单词请求

             */

            request: {

                Data : ‘‘,

                MetHod : ‘‘,

                DataType : ‘‘,

                Async : ‘‘,

 

                /**

                 * 设置请求参数

                 * @param options 请求时发送的参数对象

                 * @param method 请求方式,默认GET

                 * @param dataType 接收数据类型,默认json

                 * @param async 是否异步,默认为true

                 * @returns {Tools} 返回对象本身,以供调用send

                 */

                setData:function(options,method,dataType,async){

                    this.Data = options;

                    this.MetHod = typeof method == ‘undefined‘ ? ‘GET‘ : method;

                    this.DataType = typeof dataType == ‘undefined‘ ? ‘json‘ : dataType;

                    this.Async = typeof async == ‘undefined‘ ? true : async;

                    return this;

                },

 

                /**

                 * 发送请求

                 * @param Url 请求地址

                 * @param call 成功回调函数,可不设

                 * @param alertMessage 是否弹出确认对话框

                 * @param message 确认对话框内容

                 */

                send:function(Url,call,alertMessage,message){

                    if(!message){

                        message = "确认删除吗?";

                    }

                    if(typeof call != ‘function‘){

                        call = function(data){

                            switch(this.dataType){

                                case ‘text‘ :alert(data);break;

                                default :alert(data.message);break

                            }

                            location.reload(true);

                        }

                    }

                    var alertControl = true; //控制是否弹出提示消息

                    var sendControl = true; //控制是否发送本次请求

                    var LId;

                    if(typeof alertMessage != ‘undefined‘ && alertMessage == false){alertControl = false}

                    if(alertControl && !confirm(message)){sendControl = false;}

                    if(sendControl){

                        $.ajax({

                            url:Url,

                            type:this.MetHod,

                            data:this.Data,

                            dataType:this.DataType,

                            async:this.Async,

                            beforeSend:function(O){LId = Tools.Public.Loading.open();},

                            success:call,

                            error:function(E,Info,EO){alert(E.statusText + ":" + E.responseText);},

                            complete:function(O){Tools.Public.Loading.close(LId);}

                        });

                    }

                }

            },

 

            /**

             * 在input后添加描述文本框

             */

            Description: {

                DescId: ‘‘,

 

                /**

                 * 显示描述文字,可用于用户名/密码格式要求,在input标签上设置onfocus属性来使用

                 * @param o 使用该方法的对象,一般在input标签上使用是传入this对象

                 * @param message 显示的内容

                 */

                display: function(o,message){

                    var id = parseInt(Math.random() * 1000);

                    this.DescId = id;

                    var description = Tools.D.createElement(‘description‘);

                    description.id = id;

                    description.innerHTML = message;

                    description.style.width = "200px";

                    description.style.border = "1px solid #dfdfdf";

                    description.style.backgroundColor = "#fff";

                    description.style.lineHeight = "normal";

                    description.style.position = "absolute";

                    description.style.top = o.offsetTop + ‘px‘;

                    description.style.marginLeft = "5px";

                    $(o).after(description);

                    o.setAttribute("onblur",‘Tools.Public.Description.close()‘);

                },

                close: function(){

                    $("#"+this.DescId).remove();

                }

            },

 

            Loading : {

                WindowId:‘‘,

                open: function(message){

                    var id = parseInt(Math.random() * 1000);

                    this.WindowId = id;

                    var div = Tools.D.createElement("div");

                    div.id = id;

                    div.style.width = "80%";

                    div.style.height = "50px";

                    div.style.backgroundColor = "#000";

                    div.style.opacity = "0.5";

                    div.style.borderRadius = "10px";

                    div.style.position = "fixed";

                    div.style.top = (Tools.W.innerHeight - 50) / 2 + "px";

                    div.style.left = "10%";

                    var pTag = Tools.D.createElement("p");

                    pTag.style.textAlign = "center";

                    pTag.style.color = "#fff";

                    pTag.style.lineHeight = "50px";

                    pTag.style.height = "50px";

                    pTag.style.margin = "0";

                    var imgTag = Tools.D.createElement(‘img‘);

                    imgTag.src = "/Public/images/loading.gif"; //在这里设置加载中图标

                    imgTag.style.marginBottom = "-5px";

                    if(message){

                        pTag.innerHTML = message;

                    }else{

                        pTag.innerHTML = "正在处理中";

                    }

                    pTag.appendChild(imgTag);

                    Tools.D.body.appendChild(div);

                    Tools.GetId(this.WindowId).appendChild(pTag);

                    return id;

                },

                close:function(id){

                    if(typeof id != ‘undefined‘ && id != null){

                        Tools.D.body.removeChild(Tools.GetId(Id));

                    }else if(this.WindowId != ‘‘){

                        Tools.D.body.removeChild(Tools.GetId(this.WindowId));

                    }

                }

            }

        }

    };

})();

时间: 2024-10-24 06:54:25

一些JS常用的方法的相关文章

【js常用DOM方法】

介绍几个js DOM的常用方法 获取元素节点 getElementById  getElementsByTagName  getElementsByClassName 先写一个简单的网页做测试: /* test.html*/<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body&g

js常用小方法

1.时间格式化 a.需要熟悉Date对象的方法; b.使用  getFullYear(),getMonth(),getDate()等方法获取年份,月份等时间数据,然后根据所需要的时间格式可以自行拼接 demo: 下面以 这种格式为例:2017-09-15 15:10:06, function format(timestamp) { // 获取时间戳 Date.parse(new Date()); //timestamp是整数,否则要parseInt转换,不会出现少个0的情况 var time =

Node.js常用express方法

Node.js 手册查询-Express 方法 1.send方法 send 方法向浏览器发送一个响应信息,并可以智能处理不同类型的数据 send方法在输出响应时会自动进行一些设置,比如HEAD信息.HTTP缓存支持等等 类型可以是: String, Array, Object, Number. 当参数为一个String时,Content-Type默认设置为"text/html" 当参数为Array或Object时,Express会返回一个JSON 当参数为一个NumberExpress

原生js常用的方法

1, js数组去重的方法 //第一种 function unique(ary){ var obj={}; for(var i=0;i<ary.length;i++){ var cur = ary[i]; if(obj[cur] == cur){ ary[i] = ary[ary.length-1]; ary.length--; i--; } obj[cur] = cur; } return ary; } console.log(unique([2,3,2,4,3,5,6,1,1])); //第二

js常用通用方法

验证身份证详细方法 function isCardNo(pId) { var arrVerifyCode = [1, 0, "x", 9, 8, 7, 6, 5, 4, 3, 2]; var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; var Checker = [1, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1]; if (pId.length != 15 && pId.leng

js常用的方法

事件(事件监听) : 标签对象.事件监听.function(){执行的代码,找对象,找属性,改属性};    事件源.触发一个事件.调用一个方法.方法找执行代码找对象,找属性,改属性(或者用属性,增删改查)           onmouseover 鼠标移到某个元素之上           onmouseout  鼠标移开某个元素           onkeydown   键盘按下去(就是一直按着)           onkeypress  键盘按下去再松开(就是点击 按下去再松开)   

JS常用验证方法

1.验证必须为数字(可有小数点) if(isNaN(value))execCommand('undo') 说明:1.isNaN()方法用于验证value值是否为非法数字,返回值true或者false. 2.execCommand方法是执行一个对当前文档,当前选择或者给出范围的命令,该例子命令undo意味"撤销".因此当isNaN()返回true即"撤销"

js常用时间方法

//获取一段时间日期 YYYY-MM-DD function getDays(dayNum) { var oDate = new Date(); //获取当前时间 var dayArr = new Array(); for(var i = 0; i < dayNum; i++) { var str = new Date(oDate.getFullYear(), oDate.getMonth(), oDate.getDate() + i); dayArr.push(gmtToDate(str));

js常用字符串方法汇总

concat()将两个或多个字符的文本组合起来,返回一个新的字符串. var a = "hello"; var b = ",world"; var c = a.concat(b); alert(c); //c = "hello,world" indexOf()返回字符串中一个子串第一处出现的索引(从左到右搜索).如果没有匹配项,返回 -1 . var index1 = a.indexOf("l"); //index1 = 2