以下都是我在项目中常用的一些方法,都是通过函数的形式给出,便于即拿即用
1.获取URL中“?”符后的字符串
//如果URL后面的name携带的直接为汉字,如A.html?age=18
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
}
}
return theRequest;
}
可以直接获取age如下:let age = this.GetRequest('age')
//如果URL后面的name携带的直接为汉字,如A.html?name=兵锅锅,这种就需要解码,因为在URL中会存在乱码的情况
function getParmeter(variable){
let query = window.location.href.split('?')[1];
let vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split('=');
if(pair[0] === variable){
return pair[1];
}
}
return '';
}
可以通过如下形式获取:let age = this.getParmeter().age
2.判断字符串和数组是否为空
//String is null
function IsStringEmpty(str){
return str == undefined || str == null || Trim(str) == '' ? true : false
}
//array is null
function IsArrayEmpty(array){
return array == undefined || array == null || array.length == 0 ? true : false
}
3.如何把日期转变为指定格式
Date.prototype.format = function(fmt){
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;
}
document.getElementById("demo1").innerHTML=new Date(79,5,24,11,33,0).format("MM月dd日");
var now = new Date();
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
document.getElementById("demo2").innerHTML=new Date().format("yyyy年MM月dd日");
var nowStr = now.format("yyyy-MM-dd hh:mm:ss");
document.getElementById("demo3").innerHTML=new Date().format("yyyy年MM月dd日hh小时mm分ss秒");
//其他格式转换
alert(new Date().format("yyyy年MM月dd日"));
alert(new Date().format("MM/dd/yyyy"));
alert(new Date().format("yyyyMMdd"));
alert(new Date().format("yyyy-MM-dd hh:mm:ss"));
4.对于cookie的操作
function setCookie(name,value)
{
var Days = 30;
var exp = new Date();
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ encodeURI (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg))
return decodeURI(arr[2]);
else
return null;
}
function delCookie(name)
{
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null)
document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
5.获取url后给定name携带的值
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); // 匹配目标参数
if (r != null)
return unescape(r[2]);
return null; // 返回参数值
}
6.是否使用mock数据
//用于当前是否使用mock方式(通常在每个页面的js中会判断是否使用mock数据,一般都是将接口和模拟数据放在一个文件中,便于统一调度)
function IsMock(){
return false
}
7.时间戳的转换
// 时间戳转换
dateLongFormat:function (longTypeDate){
var date = new Date();
date.setTime(longTypeDate);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hh = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
var dateType = year + "-";
if(month <10)
dateType += "0";
dateType += month + "-" ;
if(day <10)
dateType += "0";
dateType += day + " " ;
if(hh <10)
dateType += "0";
dateType += hh+":" ;
if(mm <10)
dateType += "0";
dateType += mm+":" ;
if(ss <10)
dateType += "0";
dateType += ss ;
return dateType ;
}
8.查询年月
//查询 当天日期 返回字符串
function quesMonth(){
var date = new Date();
var year = date.getFullYear();
var mon = date.getMonth()+1;
year = year.toString();
if(mon<10){
mon = '0'+mon ;
}else{
mon = mon.toString();
}
var dateAll= year +'年'+ mon+'月' ;
return dateAll;
}
9.默认不可选日期
function getTimeByMonth(requireMonth){
var nDay = new Date().getFullYear() +'-'+(new Date().getMonth()+1) +'-'+01;
nDay = new Date(nDay).getTime();
// var curDate = (new Date()).getTime();
var Nmonth = requireMonth * 30 * 24 * 3600 * 1000;
var pastResult = nDay - Nmonth ; // n个月前的时间(毫秒单位)
pastResult = pastResult - (2 * 24 * 3600 * 1000); // 微调
return pastResult ;
}
10.上个月时间获取
lastMonth(){
var today = new Date().getTime();
var monthDay = today - (30 * 24 * 3600 * 1000);
monthDay = new Date(monthDay);
return monthDay ;
},
11.加法
//加法
accAdd: function accAdd(arg1,arg2){
arg1 = Number(arg1.toString().replace(/,/g,''));
arg2 = Number(arg2.toString().replace(/,/g,''));
var r1,r2,m;
try{
r1=arg1.toString().split(".")[1].length;
}catch(e){
r1=0 ;
}
try{
r2=arg2.toString().split(".")[1].length;
}catch(e){
r2=0 ;
}
m=Math.pow(10,Math.max(r1,r2)) ;
var temp = ( Math.ceil(arg1*m) + Math.ceil(arg2*m)) /m ;
return temp ;
},
12.获取头部信息
//获取header
function getHeaderHTML(divId){
$("html head title").empty();
$("html head title").append("业务运营平台");
var url = '***.jsp';
$.ajax({
type : "get",
async : false,
dataType : "html",
url : url,
success : function(backdata) {
$("#" + divId).append(backdata);
}
});
var url2 = '***.go';
$.ajax({
type : "get",
async : false,
url : url2,
success : function(backdata) {
if(backdata != undefined && backdata.data != undefined){
$("#" + divId +" #headLogo").attr("src","tsf/TfsServAction/fetchKey.go?picKey=" + backdata.data.orgLogo);
}else{
//$("#" + divId +" #headLogo").attr("src","../../images/head/logo.jpg");
}
}
});
}
13.获取底部信息
//获取footer
function getFooterHTML(divId) {
var url = '../../page/Common/footer.html';
$.ajax({
type: "get",
async: false,
dataType: "html",
url: url,
success: function (backdata) {
$("#" + divId).append(backdata);
}
});
var url2 = 'systemDisplay/HeadAndFootAction/getHeadAndFoot.go';
$.ajax({
type : "get",
async : false,
url : url2,
success : function(backdata) {
if(backdata != undefined && backdata.data != undefined){
$("#" + divId + " div:first" ).text(backdata.data.copyright);
}else{
}
}
});
}
14.获取前几个月的第一天和最后一天
function GetHistoryMonth(before) {
var nowdays = new Date();
var year = nowdays.getFullYear();
var month = nowdays.getMonth() + 1;
month = month - before
if (month <= 0) {
month = 12 + month;
year = year - 1;
}
month = month<10? "0"+month:month;
let startDay = "" + year + month + "01"
let endDay = "" + year + month + GetDaysInOneMonth(year, month)
return {
startDay:startDay,
endDay:endDay
}
}
15.某月有几天
function GetDaysInOneMonth(year, month) {
month = parseInt(month, 10);
var d= new Date(year, month, 0);
return d.getDate();
}
16.获取Base64
function GetBase64(imgUrl,width,height){
function GetBase64Image(img,width,height) {//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
var canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL();
return dataURL;
}
let _this = this
var image = new Image();
image.crossOrigin = '';
image.src = imgUrl;
var deferred = $.Deferred();
if(imgUrl){
image.onload =function (){
deferred.resolve(GetBase64Image(image, width, height));//将base64传给done上传处理
}
return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']
}
}