用于对数据进行排序的多个 (2) 个哈希 URL 参数

Multiple (2) hash url parameters for sorting data

本文关键字:哈希 参数 URL 数据 排序 用于      更新时间:2023-09-26

>我有 2 个过滤器:按位置和类型。每次我需要在不刷新页面的情况下更新哈希 url。我该怎么做?

链接结构,例如:site.com/about#location=12#type=188

谢谢

您可以使用

window.location.hash 调整 url 中的哈希。

window.location.hash = 'some value';
首先将

哈希拆分为#,以获得最多包含 2 个项目的数组:

var hashes = window.location.hash.split('#');

然后你可以检查它们是否存在,就像:-

var location = hashes.filter(function(i) { return i.startsWith('location'); });
var type = hashes.filter(function(i) { return i.startsWith('type'); });

如果location.length == 1并且与type相同,则设置它们。

然后,您可以像这样更新/替换:-

location[0] = "location=" + 11;
type[0] = "type=" + 190;
将它们重新连接在一起

的最简单方法是将它们重新连接在一起,未设置一个是将它们添加到新数组中并join

var arr = [];
if(location.length == 1) arr.push(location[0]);
if(type.length == 1) arr.push(type[0]);
window.location.hash = arr.join('#');