前端开发common.js 常用js方法整理

前端开发需要c 吗?| 软件开发前端工作咋样?| 前端开发需要软件工具
    var h = {};
    h.get = function (url, data, ok, error) {
        $.ajax({
            url: url,
            data: data,
            dataType: ‘json’,
            success: ok,
            error: error
        });
    }
    h.post = function (url, data, ok, error) {
        $.ajax({
            url: url,
            data: data,
            type: ‘post’,
            dataType: ‘json’,
            success: ok,
            error: error
        });
    }
    //获取url参数
    h.url = function (url) {
        if (!url) {
            url = location.search.substring(1);
        } else {
            url = url.substr(url.indexOf(‘?’) + 1);
        }
        var args = new Object(); // 声明并初始化一个 “类”
        // 获得地址(URL)”?”后面的字符串.
        var query = decodeURI(url);
        var pairs = query.split(“&”); // 分割URL(别忘了’&’是用来连接下一个参数)
        for (var i = 0; i < pairs.length; i++) {
            var pos = pairs[i].indexOf(‘=’);
            if (pos == -1) continue; // 它在找有等号的 数组[i]
            var argname = pairs[i].substring(0, pos); // 参数名字
            var value = pairs[i].substring(pos + 1); // 参数值
            // 以键值对的形式存放到”args”对象中
            args[argname] = decodeURI(value);
        }
        return args;
    }
    // 返回字符串的实际长度, 一个汉字算2个长度
    String.prototype.strlen = function () {
        returnthis.replace(/[^\x00-\xff]/g, “**”).length;
    }
    //字符串超出省略
    String.prototype.cutstr = function (len) {
        varrestr = this;
        varwlength = this.replace(/[^\x00-\xff]/g, “**”).length;
        if (wlength > len) {
            for (vark = len / 2; k < this.length; k++) {
                if (this.substr(0, k).replace(/[^\x00-\xff]/g, “**”).length >= len) {
                    restr = this.substr(0, k) + “…”;
                    break;
                }
            }
        }
        returnrestr;
    }
    //替换全部
    String.prototype.replaceAll = function (s1, s2) {
        returnthis.replace(newRegExp(s1, “gm”), s2)
    }
    //字符串去空格
    String.prototype.trim = function () {
        returnthis.replace(/(^\s*)|(\s*$)/g, “”);
    }
    String.prototype.trimAll = function () {
        returnthis.replace(/\s+/g, “”);
    }
    String.prototype.lTrim = function () {
        returnthis.replace(/(^\s*)/g, “”);
    }
    String.prototype.rTrim = function () {
        returnthis.replace(/(\s*$)/g, “”);
    }
    //判断是否以某个字符串开头
    String.prototype.startWith = function (s) {
        returnthis.indexOf(s) == 0
    }
    //判断是否以某个字符串结束
    String.prototype.endWith = function (s) {
        vard = this.length – s.length;
        return (d >= 0 && this.lastIndexOf(s) == d)
    }
    //删除数组中存在重复的元素
    functiongetUnique(someArray){
        tempArray = someArray.slice(0);//复制数组到临时数组
        for (vari = 0; i < tempArray.length; i++) {
            for (varj = i + 1; j < tempArray.length;) {
                if (tempArray[j] == tempArray[i])
                //后面的元素若和待比较的相同,则删除并计数;
                //删除后,后面的元素会自动提前,所以指针j不移动
                {
                    tempArray.splice(j, 1);
                }
                else {
                    j++;
                }
                //不同,则指针移动
            }
        }
        returntempArray;
    }
    //判断数组中是否存在重复的元素
    functionconfirmRepeat(someArray){
        tempArray = someArray.slice(0);//复制数组到临时数组
        for (vari = 0; i < tempArray.length; i++) {
            for (varj = i + 1; j < tempArray.length;) {
                if (tempArray[j] == tempArray[i])
                //后面的元素若和待比较的相同,则删除并计数;
                //删除后,后面的元素会自动提前,所以指针j不移动
                {
                    returntrue;
                }
                else {
                    j++;
                }
                //不同,则指针移动
            }
        }
        returnfalse;
    }
    //判断某个值是否在数组中
    Array.prototype.in_array = function (e) {
        for (i = 0; i < this.length; i++) {
            if (this[i] == e)
                returntrue;
        }
        returnfalse;
    }
    //判断某个值在数组中的位置
    Array.prototype.indexOf = function (e) {
        for (i = 0; i < this.length; i++) {
            if (this[i] == e)
                returni;
        }
        return -1;
    }
    //转义html标签
    functionHtmlEncode(text){
        returntext.replace(/&/g, ‘&’).replace(/\”/g, ‘”‘).replace(/</g, ‘<‘).replace(/>/g, ‘>’)
    }
    //格式化日期 DateFormat(‘yyyy_MM_dd hh:mm:ss:SS 星期w 第q季度’)
    functionDateFormat(format, date){
        if (!date) {
            date = newDate();
        }
        varWeek = [‘日’, ‘一’, ‘二’, ‘三’, ‘四’, ‘五’, ‘六’];
        varo = {
            “y+”: date.getYear(),//year
            “M+”: date.getMonth() + 1,//month
            “d+”: date.getDate(),//day
            “h+”: date.getHours(),//hour
            “H+”: date.getHours(),//hour
            “m+”: date.getMinutes(),//minute
            “s+”: date.getSeconds(),//second
            “q+”: Math.floor((date.getMonth() + 3) / 3),//quarter
            “S”: date.getMilliseconds(),//millisecond
            “w”: Week[date.getDay()]
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + “”).substr(4 – RegExp.$1.length));
        }
        for (varkino) {
            if (newRegExp(“(” + k + “)”).test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : (“00” + o[k]).substr((“” + o[k]).length));
            }
        }
        returnformat;
    }
    //设置cookie值
    functionsetCookie(name, value, Hours){
        vard = newDate();
        varoffset = 8;
        varutc = d.getTime() + (d.getTimezoneOffset() * 60000);
        varnd = utc + (3600000 * offset);
        varexp = newDate(nd);
        exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);
        document.cookie = name + “=” + escape(value) + “;path=/;expires=” + exp.toGMTString() + “;domain=360doc.com;”
    }
    //获取cookie值
    functiongetCookie(name){
        vararr = document.cookie.match(newRegExp(“(^| )” + name + “=([^;]*)(;|$)”));
        if (arr != null) returnunescape(arr[2]);
        returnnull
    }
    //加入收藏夹
    functionAddFavorite(sURL, sTitle){
        try {
            window.external.addFavorite(sURL, sTitle)
        } catch (e) {
            try {
                window.sidebar.addPanel(sTitle, sURL, “”)
            } catch (e) {
                alert(“加入收藏失败,请使用Ctrl+D进行添加”)
            }
        }
    }
    //设为首页
    functionsetHomepage(homeurl){
        if (document.all) {
            document.body.style.behavior = ‘url(#default#homepage)’;
            document.body.setHomePage(homeurl)
        } elseif(window.sidebar) {
            if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege(“UniversalXPConnect”)
                } catch (e) {
                    alert(“该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入about:config,然后将项 signed.applets.codebase_principal_support 值该为true”);
                }
            }
            varprefs = Components.classes[‘@mozilla.org/preferences-service;1’].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref(‘browser.startup.homepage’, homeurl)
        }
    }
    //跨浏览器绑定事件
    functionaddEventSamp(obj, evt, fn){
        if (!oTarget) { return; }
        if (obj.addEventListener) {
            obj.addEventListener(evt, fn, false);
        } elseif(obj.attachEvent) {
            obj.attachEvent(‘on’ + evt, fn);
        }else {
            oTarget[“on” + sEvtType] = fn;
        }
    }
    //跨浏览器删除事件
    functiondelEvt(obj, evt, fn){
        if (!obj) { return; }
        if (obj.addEventListener) {
            obj.addEventListener(evt, fn, false);
        } elseif(oTarget.attachEvent) {
            obj.attachEvent(“on” + evt, fn);
        }else {
            obj[“on” + evt] = fn;
        }
    }
    //判断是否移动设备访问
    functionisMobileUserAgent(){
        return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
    }
    //完美判断是否为网址
    functionIsURL(strUrl){
        varregular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:\@&?=+,.!\/~%\$]*)?)$/i
        if (regular.test(strUrl)) {
            returntrue;
        } else {
            returnfalse;
        }
    }
    //获取页面高度
    functiongetPageHeight(){
        varg = document, a = g.body, f = g.documentElement, d = g.compatMode == “BackCompat” ? a : g.documentElement;
        returnMath.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
    }
    //获取页面宽度
    functiongetPageWidth(){
        varg = document, a = g.body, f = g.documentElement, d = g.compatMode == “BackCompat” ? a : g.documentElement;
        returnMath.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
    }
    //获取页面可视宽度
    functiongetPageViewWidth(){
        vard = document, a = d.compatMode == “BackCompat”
            ? d.body
            : d.documentElement;
        returna.clientWidth;
    }
    //获取页面可视高度
    functiongetPageViewHeight(){
        vard = document, a = d.compatMode == “BackCompat”
            ? d.body
            : d.documentElement;
        returna.clientHeight;
    }
    //获取页面scrollLeft
    functiongetPageScrollLeft(){
        vara = document;
        returna.documentElement.scrollLeft || a.body.scrollLeft;
    }
    //获取页面scrollTop
    functiongetPageScrollTop(){
        vara = document;
        returna.documentElement.scrollTop || a.body.scrollTop;
    }
    //获取窗体可见范围的宽与高
    functiongetViewSize(){
        varde = document.documentElement;
        vardb = document.body;
        varviewW = de.clientWidth == 0 ? db.clientWidth : de.clientWidth;
        varviewH = de.clientHeight == 0 ? db.clientHeight : de.clientHeight;
        returnArray(viewW, viewH);
    }
    //随机数时间戳
    functionuniqueId(){
        vara = Math.random, b = parseInt;
        returnNumber(newDate()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a());
    }
    //获取网页被卷去的位置
    functiongetScrollXY(){
        return document.body.scrollTop ? {
            x: document.body.scrollLeft,
            y: document.body.scrollTop
        } : {
                x: document.documentElement.scrollLeft,
                y: document.documentElement.scrollTop
            }
    }
    //匹配国内电话号码(0511-4405222 或 021-87888822)
    functionistell(str){
        varresult = str.match(/\d{3}-\d{8}|\d{4}-\d{7}/);
        if (result == null) returnfalse;
        returntrue;
    }
    //匹配身份证(15位或18位)
    functionisidcard(str){
        varresult = str.match(/\d{15}|\d{18}/);
        if (result == null) returnfalse;
        returntrue;
    }
    //移动电话
    functioncheckMobile(str){
        if (!(/^1[3|5|8][0-9]\d{4,8}$/.test(str))) {
            returnfalse;
        }
        returntrue;
    }
    // 判断输入是否是一个由 0-9 / A-Z / a-z 组成的字符串
    functionisalphanumber(str){
        varresult = str.match(/^[a-zA-Z0-9]+$/);
        if (result == null) returnfalse;
        returntrue;
    }
    // 判断输入是否是有效的电子邮件
    functionisemail(str){
        varresult = str.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/);
        if (result == null) returnfalse;
        returntrue;
    }
    //金额大写转换函数 transform(‘123431233132.23’)
    functiontransform(tranvalue){
        try {
            vari = 1;
            vardw2 = newArray(“”, “万”, “亿”);//大单位
            vardw1 = newArray(“拾”, “佰”, “仟”);//小单位
            vardw = newArray(“零”, “壹”, “贰”, “叁”, “肆”, “伍”, “陆”, “柒”, “捌”, “玖”);//整数部分用
            //以下是小写转换成大写显示在合计大写的文本框中
            //分离整数与小数
            varsource = splits(tranvalue);
            varnum = source[0];
            vardig = source[1];
            //转换整数部分
            vark1 = 0;//计小单位
            vark2 = 0;//计大单位
            varsum = 0;
            varstr = “”;
            varlen = source[0].length;//整数的长度
            for (i = 1; i <= len; i++) {
                varn = source[0].charAt(len – i);//取得某个位数上的数字
                varbn = 0;
                if (len – i – 1 >= 0) {
                    bn = source[0].charAt(len – i – 1);//取得某个位数前一位上的数字
                }
                sum = sum + Number(n);
                if (sum != 0) {
                    str = dw[Number(n)].concat(str);//取得该数字对应的大写数字,并插入到str字符串的前面
                    if (n == ‘0’) sum = 0;
                }
                if (len – i – 1 >= 0) {//在数字范围内
                    if (k1 != 3) {//加小单位
                        if (bn != 0) {
                            str = dw1[k1].concat(str);
                        }
                        k1++;
                    } else {//不加小单位,加大单位
                        k1 = 0;
                        vartemp = str.charAt(0);
                        if (temp == “万” || temp == “亿”) //若大单位前没有数字则舍去大单位
                            str = str.substr(1, str.length – 1);
                        str = dw2[k2].concat(str);
                        sum = 0;
                    }
                }
                if (k1 == 3) {//小单位到千则大单位进一
                    k2++;
                }
            }
            //转换小数部分
            varstrdig = “”;
            if (dig != “”) {
                varn = dig.charAt(0);
                if (n != 0) {
                    strdig += dw[Number(n)] + “角”;//加数字
                }
                varn = dig.charAt(1);
                if (n != 0) {
                    strdig += dw[Number(n)] + “分”;//加数字
                }
            }
            str += “元” + strdig;
        } catch (e) {
            return “0元”;
        }
        returnstr;
    }
    //拆分整数与小数
    functionsplits(tranvalue){
        varvalue = newArray(”, ”);
        temp = tranvalue.split(“.”);
        for (vari = 0; i < temp.length; i++) {
            value = temp;
        }
        returnvalue;
    }
    //格式化数字
    functionnumber_format(number, decimals, dec_point, thousands_sep){
        /*
        * 参数说明:
        * number:要格式化的数字
        * decimals:保留几位小数
        * dec_point:小数点符号
        * thousands_sep:千分位符号
        * */
        number = (number + ”).replace(/[^0-9+-Ee.]/g, ”);
        varn = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeofthousands_sep === ‘undefined’) ? ‘,’ : thousands_sep,
            dec = (typeofdec_point === ‘undefined’) ? ‘.’ : dec_point,
            s = ”,
            toFixedFix = function (n, prec) {
                vark = Math.pow(10, prec);
                return ” + Math.ceil(n * k) / k;
            };
        s = (prec ? toFixedFix(n, prec) : ” + Math.round(n)).split(‘.’);
        varre = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, “$1” + sep + “$2”);
        }
        if ((s[1] || ”).length < prec) {
            s[1] = s[1] || ”;
            s[1] += newArray(prec – s[1].length + 1).join(‘0’);
        }
        returns.join(dec);
    }

目前最好的前端开发工具|web前端js开发工具|前端页面分层开发流程

» 本文来自:前端开发者 » 《前端开发common.js 常用js方法整理》
» 本文链接地址:https://www.rokub.com/4327.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!