如何使用URLSearchParams.delete()仅删除单个同名查询参数
问题根因
- 你修改的是独立于URL对象的params副本,未同步回原URL,导致修改不生效
- genres对象的key为大写开头,与页面按钮全小写的文本不匹配,无法获取到正确的类型ID做删除匹配
- 激活类切换的时序错误:先执行参数处理逻辑再切换类,导致参数处理时判断的是上一次的激活状态,逻辑完全颠倒
- URLSearchParams的delete方法原生对第二个参数的兼容性很差,直接使用会删除所有同键参数,因此你自定义的removeValue逻辑是正确的,不需要引入Promise
修复方案
1. 修正事件绑定逻辑
先切换激活类,保证后续参数判断用的是最新状态,替换原有事件绑定代码:
genres.forEach(el => el.addEventListener('click', (e) => { e.target.classList.toggle('active'); genreChoose(e); }))
2. 修正genreChoose函数的参数同步逻辑
function genreChoose(e){ // 转换按钮文本匹配genres的key规则 const btnText = e.target.innerText.replace(/( |^)[a-z]/g, (L) => L.toUpperCase()).replace(' ', '_'); let genres = { Action: 28, Adventure: 12, Animation: 16, Comedy: 35, Crime: 80, Documentary: 99, Drama: 18, Family: 10751, Fantasy: 14, History: 36, Horror: 27, Music: 10402, Mystery: 9648, Romance: 10749, Science_Fiction: 878, TV_Movie: 10770, Thriller: 53, War: 10752, Western: 37 }; const genreId = genres[btnText]; let url = new URL(lastUrl); let params = new URLSearchParams(url.search); if(e.target.classList.contains('active')){ params.append('with_genres', genreId); }else{ // 类型ID转字符串匹配params中的存储格式 params = removeValue(params, 'with_genres', String(genreId)); } // 将修改后的参数同步回URL对象 url.search = params.toString(); fetchURL(url); }
可选优化
你可以直接给每个类型按钮加data-id属性存储对应类型ID,避免文本转换的繁琐:
<div class="genre" data-id="28">action</div>
直接通过e.target.dataset.id即可获取到对应类型ID。
内容的提问来源于stack exchange,提问作者Carl
相关产品推荐
相关产品推荐

