在开发需求过程中,经常会遇到点击链接进入详情页的情况,一般的做法如下:
window.open("/xxx/xxx/xxxDetail?a=" + item.a + '&b=' + item.b);
我们也经常需要在详情页中获取url上面的参数进行一些逻辑的处理,一般的做法如下:
function getHrefParam(key) {
const search = window.location.search;
const params = new URLSearchParams(search);
return (params.get(key)) || '';
}
let a = getHrefParam(a)
let b = getHrefParam(b)
特殊情况:
当我们拼接在url上的参数存在某些特殊字符时(&、%、#、?、/ 等),getHrefParam()并不能满足我们的需求,例如:url后面的参数是:?a=xxxx#12&b=xxx&c=xxx
window.location.search方法获取的参数被“#”截断

解决方法:encodeURIComponent对参数进行一次编码即可
window.open("/xxx/xxx/xxxDetail?a=" + encodeURIComponent(item.a) + '&b=' + encodeURIComponent(item.b));

文章讲述了在开发中如何处理URL中的特殊字符,如&,%,#,?,/等,当使用`getHrefParam`函数时会遇到问题。解决方案是使用`encodeURIComponent`对参数进行编码,确保在详情页正确获取并解析URL参数。
1155

被折叠的 条评论
为什么被折叠?



