User js根据地址栏参数实现逻辑 ,可能是?a=1&b=2, ?a=1 也可能是地址栏上面一开始是?a=1,然后进行拼接出?a=1&b=2&c=1 这样 的

44 阅读2分钟

在JavaScript中,你可以通过 window.location.search 获取URL地址栏中的查询字符串部分(即问号?之后的部分),然后进行解析和操作。

下面是一个基础的示例,展示了如何根据地址栏参数实现逻辑:

// 获取地址栏参数
function getQueryParams() {
  const params = {};
  const queryString = window.location.search.substring(1);
  const queries = queryString.split("&");

  queries.forEach((query) => {
    const [key, value] = query.split("=");
    params[key] = decodeURIComponent(value);
  });

  return params;
}

// 设置地址栏参数
function setQueryParams(newParams) {
  const params = { ...getQueryParams(), ...newParams };
  const queries = [];

  for (const [key, value] of Object.entries(params)) {
    queries.push(`${key}=${encodeURIComponent(value)}`);
  }

  const newQueryString = "?" + queries.join("&");
  history.pushState({}, null, window.location.pathname + newQueryString);
}

// 示例使用
document.addEventListener("DOMContentLoaded", () => {
  const params = getQueryParams();

  // 初始逻辑
  if (params.a === "1" && !params.b) {
    console.log("参数 a 是 1,但没有参数 b");
  } else if (params.a === "1" && params.b === "2") {
    console.log("参数 a 是 1,参数 b 是 2");
  }

  // 假设某个动作触发了参数的改变
  setTimeout(() => {
    setQueryParams({ b: "2", c: "1" });
    console.log("参数已更新");
  }, 3000);
});

抱歉,我误解了你的需求。如果你想根据地址栏参数来改变页面逻辑,你可以像下面这样做:

  1. 获取地址栏参数: 使用 window.location.search 获取URL的查询字符串。
  2. 解析参数: 将查询字符串解析为一个JavaScript对象。
  3. 执行逻辑: 根据解析后的参数执行相应的逻辑。
  4. 更新地址栏参数: 如果需要,你还可以更新地址栏的参数。

下面是代码示例:

// 获取地址栏参数并解析为一个对象
function getQueryParams() {
  const params = {};
  const queryString = window.location.search.substring(1);
  const queries = queryString.split('&');

  queries.forEach((query) => {
    const [key, value] = query.split('=');
    params[key] = decodeURIComponent(value);
  });

  return params;
}

// 更新地址栏参数
function updateQueryParams(newParams) {
  const params = { ...getQueryParams(), ...newParams };
  const updatedQueries = [];

  for (const [key, value] of Object.entries(params)) {
    updatedQueries.push(`${key}=${encodeURIComponent(value)}`);
  }

  const newQueryString = '?' + updatedQueries.join('&');
  history.pushState({}, null, window.location.pathname + newQueryString);
}

// 执行逻辑
document.addEventListener("DOMContentLoaded", () => {
  const params = getQueryParams();

  if ('a' in params) {
    // 如果地址栏有参数 a
    // 在这里执行你的逻辑
    if(params.a === "1") {
      // 比如:改变某个div的内容
      document.getElementById("someDiv").textContent = "参数a是1";
    }
  }

  if ('b' in params) {
    // 如果地址栏有参数 b
    // 在这里执行你的逻辑
    if(params.b === "2") {
      // 比如:改变某个div的颜色
      document.getElementById("someDiv").style.backgroundColor = "red";
    }
  }

  // 假设你在某个点想要更新地址栏参数
  setTimeout(() => {
    updateQueryParams({ c: '1' });
    // 这时地址栏会变成 ?a=1&b=2&c=1(如果原来就有 a 和 b 的话)
  }, 3000);
});

在这个示例中,我定义了两个函数:getQueryParams() 用于获取和解析地址栏的参数,updateQueryParams() 用于更新地址栏的参数。然后,我在 DOMContentLoaded 事件触发后根据这些参数执行了一些逻辑。

你可以根据实际情况调整这个示例。希望这能帮到你!