JavaScript經常使用方法(工具類的封裝)

日期格式化javascript

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;
};
 
new Date().format("yyyy-MM-dd hh:mm")  
 
距離格式化
 convertDistanceStr = function(distance) {
     if  (!distance) {
         return  "" ;
     else  if  (distance < 1000) {
         return  distance +  "m"
     else  if  (distance >= 1000 && distance < 100000) {
         return  (distance / 1000.0).toFixed(1) +  "km"
     else  if  (distance > 100000) {
         return  (distance / 1000.0).toFixed(0) +  "km"
     else  {
         return  "" ;
     }
};

 

格式驗證html

checkStr (str, type) {
    switch (type) {
        case 'phone':   //手機號碼
            return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
        case 'tel':     //座機
            return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
        case 'card':    //身份證
            return /^\d{15}|\d{18}$/.test(str);
        case 'pwd':     //密碼以字母開頭,長度在6~18之間,只能包含字母、數字和下劃線
            return /^[a-zA-Z]\w{5,17}$/.test(str)
        case 'postal':  //郵政編碼
            return /[1-9]\d{5}(?!\d)/.test(str);
        case 'QQ':      //QQ號
            return /^[1-9][0-9]{4,9}$/.test(str);
        case 'email':   //郵箱
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
        case 'money':   //金額(小數點2位)
            return /^\d*(?:\.\d{0,2})?$/.test(str);
        case 'URL':     //網址
            return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
        case 'IP':      //IP
            return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
        case 'date':    //日期時間
            return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
        case 'number':  //數字
            return /^[0-9]$/.test(str);
        case 'english': //英文
            return /^[a-zA-Z]+$/.test(str);
        case 'chinese': //中文
            return /^[\u4E00-\u9FA5]+$/.test(str);
        case 'lower':   //小寫
            return /^[a-z]+$/.test(str);
        case 'upper':   //大寫
            return /^[A-Z]+$/.test(str);
        case 'HTML':    //HTML標記
            return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
        default:
            return true;
    }
}

 

讀取url參數java

getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2]);
    }
    return "";
};

 

讀取所有url參數web

getUrlParams = function (url) {
    var params = {};
    var search = url.search;
    if (search) {
        while (search.indexOf("?") == 0) {
            search = search.substr(1);
        }
        var arr = search.split("&");
        for (var i = 0; i < arr.length; i++) {
            var kv = arr[i].split("=");
            if (kv.length >= 2) {
                params[kv[0]] = decodeURIComponent(kv[1]);
            }
        }
    }
    return params;
};

初始化評分星星ajax

<span class="score-stars" data-value=""></span><br>initScoreStars = function () {
    $(".score-stars").each(function (index, item) {
        var value = parseFloat($(item).attr("data-value"));
        var stars = "";
        for (var i = 0; i < 5; i++) {
            if (value - i >= 0.9) {
                stars += "<i class='iconfont icon-star'></i>";
            } else if (value - i >= 0.1) {
                stars += "<i class='iconfont icon-starhalf'></i>";
            } else {
                stars += "<i class='iconfont icon-star muted'></i>";
            }
        }
        $(item).html(stars);
    });
};

判斷是不是pc端json

isPC () { //是否爲PC端
     var  userAgentInfo = navigator.userAgent;
     var  Agents = [ "Android" "iPhone" ,
                 "SymbianOS" "Windows Phone" ,
                 "iPad" "iPod" ];
     var  flag =  true ;
     for  ( var  v = 0; v < Agents.length; v++) {
         if  (userAgentInfo.indexOf(Agents[v]) > 0) {
             flag =  false ;
             break ;
         }
     }
     return  flag;
}

判斷是否爲微信端api

isWXBrowser = function () {
    return navigator.userAgent.toLowerCase().indexOf("micromessenger") >= 0;
}

微信支付簽名時間戳,簽名隨機串微信

var timestamp = Math.round(new Date().getTime() / 1000).toString();//時間戳
    var nonceStr = Math.round(Math.random() * 100000000).toString();隨機串

http請求app

app.getJSON = function (url, data, successFunc, errorFunc) {
    app.request("get", url, data, successFunc, errorFunc);
}
 
app.delete = function (url, data, successFunc, errorFunc) {
    app.request("delete", url, data, successFunc, errorFunc);
}
 
// 提交數據
app.post = function (url, data, successFunc, errorFunc) {
    app.request("post", url, data, successFunc, errorFunc);
}
 
app.put = function (url, data, successFunc, errorFunc) {
    app.request("put", url, data, successFunc, errorFunc);
}
 
app.request = function (method, url, data, successFunc, errorFunc) {
    if (method.toLowerCase() == "post" || method.toLowerCase() == "put") {
        if (data && typeof  data != "string") {
            data = JSON.stringify(data);
        } else if (!data) {
            data = "";
        }
    }
 
    $.ajax({
        type: method,
        dataType: "json",
        url: url,
        data: data,
        contentType: "application/json",
        beforeSend: function (request) {
            request.setRequestHeader("appKey", conf.appKey);
        },
        success: function (res) {
            if (res.status == "9901") {
                var baseUrl;
                if(window.location.href.toString().indexOf("/new/")>0){
                    baseUrl=conf.newWebBaseUrl;
                }
                else if(window.location.href.toString().indexOf("/newStore/")>0){
                    baseUrl=conf.newStoreBaseUrl;
                }
                else {
                    baseUrl=conf.webBaseUrl;
                }
            } else if (typeof successFunc == "function") {
                successFunc(res);
            }
        },
        error: function () {
            if (typeof errorFunc == "function") {
                errorFunc();
            }
        }
    });
}
 
用法
    app.getJSON(conf.apiBaseUrl + "/users/updAutoRebateMerchant", {
            merchantId:merchantId
        }, function (res) {
            if (res.status == "0000") {
               //成功
            } else if (res.message) {
                mui.alert(res.message);
            }
        });
相關文章
相關標籤/搜索