首页 > 解决方案 > How can I take parameters from a url and append them to different tiles on the website?

问题描述

I have a website where visitors can select filters to find a vacation. When you navigate to a country there are four tiles atop the page with regions or cities. I'd like to take parameters from the URL and attach them to the new url when you click on any of these tiles. This is my code:

var arr = window.location.search.split('?')[1].split('&');
var filters = "";
$(arr).each(function (i) {
    if (arr[i].indexOf("geo=") === -1 && arr[i].indexOf("order=") === -1 && arr[i].indexOf("theme=") === -1) {
      filters = filters.concat("&", arr[i]);
   }    
});
$("a.vak-card__content.vak-card__content--overlaid").each(function (i) {
    var href = $("a.vak-card__content.vak-card__content--overlaid:eq(" + i + ")").attr("href");
    if (href.indexOf("geo=") != -1) {
        href = href.split("&search=yes")[0].concat(filters);
        $("a.vak-card__content.vak-card__content--overlaid:eq(" + i + ")").attr("href", href);
    }
});

The only problem is that above code doesn't take double values into consideration. The challenge is to determine filters from current URL both with a value and without a value, then to exclude filters without a value for all tiles, compare with filters from URL and finally if a filter is not included in the URL to add it to the tile (new URL). I know it sounds convoluted, I wish I could explain it more clearly.

The filters I'm talking about (parameters in the URL):

标签: javascriptjqueryurlfilterparameters

解决方案


你为什么不试试原生的 URLSearchParams 工具呢? https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

我真的不明白你想包括什么然后排除:) 但有了这个你可以创建偶数集或得到所有。希望能帮助到你。


推荐阅读