js修改URL参数,修改后可刷新页面也可以不刷新页面
//paramName=参数名称,replaceWith=参数值,isRefresh=是否刷新(0不刷新,1刷新) //使用方法:replaceParamVal("userId", "333", 0) function replaceParamVal(paramName, replaceWith, isRefresh) { var oUrl = this.location.href.toString(); if (paramName && replaceWith) { if (oUrl.indexOf(paramName + "=" + replaceWith) > 1) { return; } } if (oUrl.indexOf('&' + paramName + '=') > 0) { var re = eval('/(&' + paramName + '=)([^&]*)/gi'); var nUrl = oUrl.replace(re, '&' + paramName + '=' + replaceWith); } else { if (oUrl.indexOf("?") > 0) { var nUrl = oUrl + "&" + paramName + "=" + replaceWith; } else { var nUrl = oUrl + "?" + paramName + "=" + replaceWith; } } // this.location = nUrl; if (isRefresh) { window.location.href = nUrl } var stateObject = { id: "" }; var title = ""; history.replaceState(stateObject, title, nUrl); } $(function () { $("#test1").click(function () { replaceParamVal("userId", "333", 0)//不刷新 }) $("#test2").click(function () { replaceParamVal("userId", "555", 1)//刷新 }) })
js获取参数的方法
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; };
标签:function,nUrl,oUrl,URL,replaceWith,js,网址,paramName,var From: https://www.cnblogs.com/webapi/p/16721551.html