在 href 中添加多个 GET 值

Adding more than one GET value in the href

我得到这个 HTML 有几个无序列表。

<ul>
    <h3>Staff</h3>
    <li><a href="?staff=Mike">Mike</a></li>
    <li><a href="?staff=John">John</a></li>
    <li><a href="?staff=Kyle">Kyle</a></li>
</ul>
<ul>
    <h3>Category</h3>
    <li><a href="?category=Food">Food</a></li>
    <li><a href="?category=Sports">Sports</a></li>
    <li><a href="?category=News">News</a></li>
    <li><a href="?category=Games">Games</a></li>
    <li><a href="?category=GIFs">GIFs</a></li>
</ul>

可以看出,它们的每个 href 都包含参数值。我的问题是:使用 Javascript,如果其中一个在 URL.

中处于活动状态,我如何在 href 的参数中附加一个新值

即: URL 是 www.site.com/?category=Food.

因此列表的价值应为:

<ul>
    <h3>Staff</h3>
    <li><a href="?category=Food&staff=Mike">Mike</a></li>
    <li><a href="?category=Food&staff=John">John</a></li>
    <li><a href="?category=Food&staff=Kyle">Kyle</a></li>
</ul>
<ul>
    <h3>Category</h3>
    <li><a href="?category=Food">Food</a></li>
    <li><a href="?category=Food,Sports">Sports</a></li>
    <li><a href="?category=Food,News">News</a></li>
    <li><a href="?category=Food,Games">Games</a></li>
    <li><a href="?category=Food,GIFs">GIFs</a></li>
</ul>

你能做的是

  1. 将当前查询字符串解析为一个URLSearchParams对象
  2. 对于每个 <a> 元素,将 href 解析为一个 URL 对象
  3. 迭代步骤#1 中的查询参数并...
    1. 检查参数是否已经存在
    2. 如果没有,只需附加它
    3. 如果是,则将当前 list 解析为 Set,添加查询字符串中的值,然后将值写回 URL
  4. URL写入<a>href属性

//const query = location.search
const query = "?category=Food" // this is for the snippet

// Parse any CSV values into arrays and store in a `Map`
const params = new Map()
for (let [ key, val ] of (new URLSearchParams(query))) {
  params.set(key, val.split(","))
}

const links = document.querySelectorAll("ul li a[href]")

links.forEach(link => {
  const url = new URL(link.href)
  
  // Loop the page query params
  for (let [ param, values ] of params) {
    if (url.searchParams.has(param)) {
      // Split the current value on "," and parse to a `Set`
      const linkParams = new Set(url.searchParams.get(param).split(","))
      
      // Add the query string value then write the param back into the URL
      values.forEach(v => linkParams.add(v))
            
      url.searchParams.set(param, [...linkParams].join(","))
    } else {
      // Simply append the param value 
      url.searchParams.append(param, values.join(","))
    }
  }
  link.href = url
})
/* This just makes it easy to see the URLs in the demo */
a[href]:after {
  content: " - " attr(href);
  font-size: .8;
  color: grey;
}
<ul>
    <h3>Staff</h3>
    <li><a href="?staff=Mike">Mike</a></li>
    <li><a href="?staff=John">John</a></li>
    <li><a href="?staff=Kyle">Kyle</a></li>
</ul>
<ul>
    <h3>Category</h3>
    <li><a href="?category=Food">Food</a></li>
    <li><a href="?category=Sports">Sports</a></li>
    <li><a href="?category=News">News</a></li>
    <li><a href="?category=Games">Games</a></li>
    <li><a href="?category=GIFs">GIFs</a></li>
</ul>