JavaScript常用方法(工具类的封装)
日期格式化
function formatDateTime(timeStamp) {
var date = new Date();
date.setTime(timeStamp);
var y = date.getFullYear();
var m = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
var d = date.getDate();
d = d < 10 ? ('0' + d) : d;
var h = date.getHours();
h = h < 10 ? ('0' + h) : h;
var minute = date.getMinutes();
var second = date.getSeconds();
minute = minute < 10 ? ('0' + minute) : minute;
second = second < 10 ? ('0' + second) : second;
// return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
return y + '-' + m + '-' + d;
}
formatDateTime("1592659874256")
距离格式化
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 ""; } };
格式验证
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参数
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参数
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; };
初始化评分星星
<span class="score-stars" data-value=""></span>
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端
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; }
判断是否为微信端
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.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); } });