js修改网址URL参数后实现刷新和不刷新
//获取URL参数 function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) { return decodeURI(r[2]); } return null; }; //name=参数名称,val=参数值,isRefresh=是否刷新(0不刷新,1刷新) //使用方法:replaceParamVal("id", "888", 0) function replaceParamVal(name, val, isRefresh) { var url = this.location.href.toString(); //console.log(url); var pattern = "[\?]" + name + '=([^&]*)'; var pattern2 = "[&]" + name + '=([^&]*)'; var replaceText = name + '=' + val; var replaceText1 = "\?" + replaceText; var replaceText2 = "&" + replaceText; if (url.match(pattern)) { var tmp = '/\\?(' + name + '=)([^&]*)/gi'; var nUrl = url.replace(eval(tmp), replaceText1);; } else if (url.match(pattern2)) { var tmp = '/&(' + name + '=)([^&]*)/gi'; var nUrl = url.replace(eval(tmp), replaceText2);; } else { if (url.match('[\?]')) { var nUrl= url + '&' + replaceText; } else { var nUrl= url + '?' + replaceText; } } if (isRefresh) { window.location.href = nUrl } var stateObject = { id: "" }; var title = ""; history.replaceState(stateObject, title, nUrl); } $(function () { $("#test1").click(function () { replaceParamVal("id", "333", 0)//不刷新 }) $("#test2").click(function () { replaceParamVal("id", "555", 1)//刷新 }) }) document.write(GetQueryString("id"))