在具有多个值的查询字符串参数上使用indexof

时间:2015-09-17 10:13:12

标签: javascript jquery query-string

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

查询字符串: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而不是第二个或第三个。

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

2 个答案:

答案 0 :(得分:3)

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

    }

答案 1 :(得分:2)

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

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

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

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

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