gpt4 book ai didi

javascript - 基于复选框添加和删除 URL 参数

转载 作者:行者123 更新时间:2023-11-30 09:11:46 25 4
gpt4 key购买 nike

我有一些过滤器在我的网站上显示为复选框。每次有人选中或取消选中这些输入之一时,我要么想向 URL 添加过滤器,要么从 URL 中删除过滤器。这主要是我的工作,但问题出现在删除列表中的最后一个过滤器时。

这是一个例子:

var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;

for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');

if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};

$(function () {
var colors = getUrlParameter('colors');
var currentUrl = location.href;

$('input[type="checkbox"]').change(function () {
var inputVal = $(this).val();

if (this.checked) {
// Add filter to URL params
colors = getUrlParameter('colors');
if (!colors) {
// No filters exist yet
currentUrl += '?colors=' + inputVal;
} else {
// At least one filter exists
currentUrl += ',' + inputVal;
}
console.log(currentUrl);
window.history.pushState("object or string", "Title", currentUrl);
} else {
// Remove filter from URL params
currentUrl = currentUrl.replace(inputVal + ',', '');
console.log(currentUrl);
window.history.pushState("object or string", "Title", currentUrl);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="filters">
<label><input type="checkbox" value="blue" />Blue</label>
<label><input type="checkbox" value="red" />Red</label>
<label><input type="checkbox" value="green" />Green</label>
</div>

如果颜色是第一个(如果有或其他过滤器)或在过滤器列表的中间,这会起作用,因为它匹配我的 replace(),想知道我如何动态地做到这一点它会在必要时同时删除颜色和逗号,或者如果没有选中,则完全删除 colors=

例如,如果选中所有 3 种颜色,则 url 将如下所示:

http://example.net?colors=blue,red,green

如果您随后删除 blue,它应该如下所示:

http://example.net?colors=red,green

如果你然后删除绿色,它看起来像这样:

http://example.net?colors=red

最后,去除红色看起来像这样:

http://example.net

最佳答案

您需要将颜色拆分到一个数组中,然后在最后再次将其合并。

$(function () {
var colors = getUrlParameter('colors');
var currentUrl = location.href;

$('input[type="checkbox"]').change(function () {
var inputVal = $(this).val();
var colorsQuery = getUrlParameter('colors') || "";
//Split into an array after each `,`
colors = colors.split(",");
if (this.checked) {
//Add to our current colors
colors.push(inputVal);
} else {
// Remove from our current colors
const index = colors.indexOf(inputValue);
colors.splice(index, 1);
}
colorString = "";
if(colors.length){
//Merge back into a string with a `,`
colorString = "?colors=" + colors.join(",")
}
window.history.pushState("object or string", "Title", currentUrl + colorString);
});
});

在这种情况下使用数组要容易得多,所以我们只是 splitjoin将字符串与数组相互转换。

为了增加它的简单性,我们可以直接推到我们的数组上

要删除一种颜色,我们要找出它在我们的颜色数组中的位置。然后使用 splice从我们的数组中删除它。

关于javascript - 基于复选框添加和删除 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com