浏览器url增加参数并跳转问题

1,058 阅读1分钟

问题:

前端页面如何在不改变url的情况下增加参数?
url增加参数后怎么跳转?回退后变成无参数而且能刷新?

相反,怎么在不改变url的情况下删除参数并跳转?

解决:
增加参数并跳转代码块:

function insertParam(key, value) {
  key = encodeURI(key);
  value = encodeURI(value);
  var kvp = document.location.search.substr(1).split('&');
  var i = kvp.length;
  var x;
  while (i--) {
    x = kvp[i].split('=');
    if (x[0] == key) {
      x[1] = value;
      kvp[i] = x.join('=');
      break;
    }
  }
  if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
  window.history.pushState(null, null, document.location.origin + document.location.pathname + '?' + kvp.join('&'));
}
//使用:
insertParam('year',2020);

删除参数并跳转代码块:

function deleteParam(name) {
  var loca = window.location;
  var baseUrl = loca.origin + loca.pathname + "?";
  var query = loca.search.substr(1);
  var kvp = document.location.search.substr(1).split('&');

  if (query.indexOf(name) > -1) {
    var obj = {}
    var arr = query.split("&");
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split("=");
      obj[arr[i][0]] = arr[i][1];
    }
    delete obj[name];
    var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
    if (url.length == url.lastIndexOf('?') + 1) {
      window.history.pushState(null, null, document.location.origin + document.location.pathname);
    } else {
      window.history.pushState(null, null, url);
    }
  }
}
//使用:
deleteParam('year');