这篇文章主要介绍的是JavaScript重定向URL参数的两种方法,下面话不多说,直接看示例代码。
一、字符拼接形式
if (strUrl.indexOf("?") != -1) {
strUrl = strUrl.substr(strUrl.indexOf("?") + 1); //<a href="https://www.jb51.cc/tag/huoqu/" target="_blank" class="keywords">获取</a>参数
if (strUrl.toLowerCase().indexOf(para.toLowerCase()) == -1) { //如果没有找到参数,则直接赋值
strNewUrl = url + "&" + para + "=" + val;
window.location.href = strNewUrl;
} else {
var aParam = strUrl.split("&");
for (var i = 0; i < aParam.length; i++) {
if (aParam[i].substr(0,aParam[i].indexOf("=")).toLowerCase() == para.toLowerCase()) {
aParam[i] = aParam[i].substr(0,aParam[i].indexOf("=")) + "=" + val;
}
}
strNewUrl = url.substr(0,url.indexOf("?") + 1) + aParam.join("&");
window.location.href = strNewUrl;
}
} else {
strUrl += "?" + para + "=" + val;
window.location.href = strUrl;
}
}</pre>
二、利用正则
var reg = new RegExp("(^|)" + para + "=([^&]*)(|$)");
if (reg.test(pars)) { //有需要的参数para
var p1 = pars.split(para)[0]; //productID=100857&count=1&
var p2 = pars.split(para)[1]; //=75825&coupval=1.5&addressID=358&invoiceID=1245&invoiceName=jesse
if (p2.indexOf("&") > -1) {
var p3 = p2.split("&")[0];
if (p3 == "=" + val + "") {
return false;
}
newpar = p1 + para + '=' + val + '&' + (p2.split(p3))[1];
} else {
if (p1) {
newpar = p1 + para + '=' + val;
} else {
newpar = para + '=' + val;
}
}
} else {
if (url.indexOf("?") == -1) {
newpar = pars +"&"+ para + "=" + val;
} else {
newpar = pars + "&" + para + "=" + val;
}
}
window.location.href = location.href.split('?')[0] + "?" + newpar;
}</pre>
调用:
window.onload = function () {
var btn = document.getElementById("btnClick");
btn.onclick = function () {
// URL地址:http://localhost:54714/testuri.aspx?productID=100857&count=1&coupresId=12785&coupval=1.5&openId=12456&addressID=358&invoiceID=&invoiceName=
//setUri("coupresId",0);
setPara("coupresId",0);
}
}