使用ES6风格,变量声明多用let const。
1、获取URL绝对路径(去掉域名与参数)
function getUrlAbsolutePath() {
const url = location.href,
arrUrl = url.split("//"),
start = arrUrl[1].indexOf("/");
let relUrl = arrUrl[1].substring(start); //截取从start开始到结尾的所有字符
if (relUrl.indexOf("?") != -1) {
relUrl = relUrl.split("?")[0];
}
return relUrl;
}
2、获取URL中的参数
function getParams() {
const url = location.search; //获取url中"?"符后的字符串
let theRequest = {};
if (url.indexOf("?") != -1) {
const str = url.substr(1),
strs = str.split("&");
for(let i = 0; i < strs.length; i ++) {
let arrParam = strs[i].split("=");
theRequest[arrParam[0]] = unescape(decodeURIComponent(arrParam[1]));//中文字符
}
}
return theRequest;
}
3、获取指定的参数
function getQueryString(name) {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const r = location.search.substr(1).match(reg);
if (r) {
return unescape(r[2]);
}
return null;
}
4、Ajax请求显示加载中
$.ajax({
type: "post",
url: loadurl,
async: true,
t: new Date().getTime(), //时间戳
success(data) {
$("#test").html(data);
}
beforeSend() {
$("#test").html('加载中...');
}
});
5、字符串大小长度获取(支持中文)
在字符串没有中文的情况用str.length直接获取,是可以的。因为中文占两个字节,所以在包含中文字符串的情况下,这样是不正确的。
function getRealLen(str) {
///<summary>获得字符串实际长度</summary>
///<param name="str">要获取长度的字符串</param>
let realLength = 0,
len = str.length,
charCode = -1;
for (let i = 0; i < len; i++) {
let charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128)
realLength += 1;
else
realLength += 2;
}
return realLength;
};
6、window.open打开之后弹窗后再关闭刷新本页面
使用window.open打开弹窗后,在弹窗页面关闭时,上级页面刷新。(注:此函数放置在父页面中)
function openWin(url,text,winInfo){
const winObj = window.open(url,text,winInfo);
let loop = setInterval(function() {
if(winObj.closed) {
clearInterval(loop);
location.reload();
}
}, 1);
}