【问题标题】:using indexof on query string parameter with multiple values在具有多个值的查询字符串参数上使用 indexof
【发布时间】:2023-04-02 19:05:02
【问题描述】:

我根据从另一个页面解析的查询字符串参数的内容显示隐藏的 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 而不是第二个或第三个。

我知道这将是一个简单的解决方案 - 有点卡住了。任何帮助表示赞赏!

【问题讨论】:

标签: javascript jquery query-string


【解决方案1】:

您需要删除 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();

    }

【讨论】:

  • 这在技术上是正确的,但我不会在代码审查中接受它。
  • 因为它不必要地(并且不必要地)一遍又一遍地重复代码,而不是参数化操作。它也容易出错(正如 OP 发现的那样)
【解决方案2】:

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

然后,您应该使用 same 类(例如 content)标记 所有 内容元素,以便您可以在运行 @ 之前对所有内容元素进行 .hide() 987654324@ 在您想要保持可见的那些上。正如所写的那样,任何已经可见的元素在您弹出状态时都将保持可见,即使它们不应该是。

你的参数提取代码没问题,但是得到你的 q1 值我会这样做:

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

从而删除所有(损坏的)条件逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多