1、设置地址栏参数
function setQueryString(key, val) { //传进想设置querystring的key和value var search = location.search.substr(1); //获取地址栏 "?"后的内容 var query = {}; if (search) { search.split('&').forEach((item) => { var arr = item.split('='); query[arr[0]] = arr[1]; }); } query[key] = val; var queryArr = []; for (var p in query) { queryArr.push(p + '=' + query[p]); } history.replaceState(null, null, '?' + queryArr.join('&')); };
2、获取地址栏参数
function getQueryString(name) { //传进想要获取的querystring的key var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return decodeURIComponent(r[2]); return null; };