用new覆盖现有的URL参数值

时间:2017-02-20 08:47:09

标签: javascript jquery

我希望此代码替换现有的URL参数“aspid”,但它的作用是在现有的id上添加另一个id。有人可以帮忙吗?

$(document).ready(function() {

  function GetUrlValue(VarSearch) {
    var SearchString = window.location.search.substring(1);
    var VariableArray = SearchString.split('&');
    for (var i = 0; i < VariableArray.length; i++) {
      var KeyValuePair = VariableArray[i].split('=');
      if (KeyValuePair[0] == VarSearch) {
        return KeyValuePair[1];
      }
    }
  }

  var asid = GetUrlValue('aspid');
  var campaign = GetUrlValue('utm_campaign');
  if (asid != undefined) {
    $("a").attr('href', function(i, h) {
      return h + (h.indexOf('?') != -1 ? "&aspid=" + asid : "?aspid=" + asid);
    });
  }
});

1 个答案:

答案 0 :(得分:1)

您需要在每个a

上调用此函数
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
  var newAdditionalURL = "";
  var tempArray = url.split("?");
  var baseURL = tempArray[0];
  var additionalURL = tempArray[1];
  var temp = "";
    if (additionalURL) {
      tempArray = additionalURL.split("&");
      for (var i=0; i<tempArray.length; i++){
          if(tempArray[i].split('=')[0] != param){
              newAdditionalURL += temp + tempArray[i];
              temp = "&";
          }
      }
  }

  var rows_txt = temp + "" + param + "=" + paramVal;
  return baseURL + "?" + newAdditionalURL + rows_txt;
}

然后像这样调用函数:

updateURLParameter(window.location.href, 'paramName', 'Value')

完整代码如:

...
$("a").attr('href', function(i, h) {
 if(h){
   return updateURLParameter(h, 'aspid', asid);
 }
});
...