问题描述
我得到了包含几个无序列表的 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 中包含 params 值。我的问题是:使用 Javascript,如果其中一个在 URL 中处于活动状态,我如何在 href 的参数中附加一个新值。
浏览器: 网址为 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>
解决方法
你能做的是
- 将当前查询字符串解析为
URLSearchParams
对象 - 对于每个
<a>
元素,将href
解析为一个URL
对象 - 迭代第 1 步中的查询参数,然后...
- 检查参数是否已经存在
- 如果没有,只需附加它
- 如果是,则将当前 list 解析为
Set
,添加查询字符串中的值,然后将该值写回URL
- 将
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>