对具有多个值的查询字符串参数使用索引

using indexof on query string parameter with multiple values

本文关键字:参数 字符串 索引 查询      更新时间:2023-09-26

我根据从另一个页面解析的查询字符串参数的内容显示隐藏div,使用indexof检查值是否存在-然后显示该值对应的div。

查询字符串:index.html?q1=bag1,bag2,bag3

    var urlParams;
    (window.onpopstate = function () {
        var match,
            pl     = /'+/g,  // Regex for replacing addition symbol with a space
            search = /([^&=]+)=?([^&]*)/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            query  = window.location.search.substring(1);
        urlParams = {};
        while (match = search.exec(query))
           urlParams[decode(match[1])] = decode(match[2]);
    })();

然后使用indexOf显示基于值的div:

    if ((urlParams["q1"]).indexOf("bag1") >= 0) {
        $(".content1").show();
    } else
    if ((urlParams["q1"]).indexOf("bag2") >= 0) {
        $(".content2").show();
    } else
    if ((urlParams["q1"]).indexOf("bag3") >= 0) {
        $(".content3").show();
    }

但是,它只显示第一个div,而不显示第二个或第三个。

我知道这将是一个简单的解决方案-有点卡住了。任何帮助,感谢!

您需要删除else子句,因为解释器将在第一个if为真后停止。所以你的代码应该看起来像

    if ((urlParams["q1"]).indexOf("bag1") >= 0) {
        $(".content1").show();
    }
    if ((urlParams["q1"]).indexOf("bag2") >= 0) {
        $(".content2").show();
    }
    if ((urlParams["q1"]).indexOf("bag3") >= 0) {
        $(".content3").show();
    }

我建议使用您的bag1等值作为id而不是类来识别单独的内容部分。如果一个类只标识一个元素,那么你就做错了。

然后你应该用相同的类标记所有内容元素(例如content),这样你就可以在所有这些元素上运行.hide(),然后在你想要保持可见的元素上运行.show。如前所述,当你弹出state时,任何已经可见的元素都将保持可见,即使它们不应该是可见的。

你的参数提取代码是可以的,但是已经得到了你的q1值,我就这样做:

var q1 = urlParams.q1;
if (q1 !== undefined) {
    $('.content').hide();    // show nothing
    q1.split(',').forEach(function(id) {
        $('#' + id).show();
    });
}

从而删除所有(破碎的)条件逻辑。