在具有多个值的查询字符串参数上使用 indexof
using indexof on query string parameter with multiple values
我根据从另一个页面解析的查询字符串参数的内容显示隐藏的 divs,使用 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
根据值显示divs:
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 而不是 classes 来标识单独的内容部分。如果 class 只标识一个元素,那么你做错了。
然后您应该使用 same class 标记 all 内容元素(例如 content
)这样您就可以在 运行 .show
之前对所有这些 .hide()
进行显示。如所写,任何已经可见的元素在弹出状态时将保持可见,即使它们不应该是可见的。
你的参数提取代码没问题,但是得到你的 q1
值后我会这样做:
var q1 = urlParams.q1;
if (q1 !== undefined) {
$('.content').hide(); // show nothing
q1.split(',').forEach(function(id) {
$('#' + id).show();
});
}
从而删除所有(损坏的)条件逻辑。
我根据从另一个页面解析的查询字符串参数的内容显示隐藏的 divs,使用 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
根据值显示divs:
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 而不是 classes 来标识单独的内容部分。如果 class 只标识一个元素,那么你做错了。
然后您应该使用 same class 标记 all 内容元素(例如 content
)这样您就可以在 运行 .show
之前对所有这些 .hide()
进行显示。如所写,任何已经可见的元素在弹出状态时将保持可见,即使它们不应该是可见的。
你的参数提取代码没问题,但是得到你的 q1
值后我会这样做:
var q1 = urlParams.q1;
if (q1 !== undefined) {
$('.content').hide(); // show nothing
q1.split(',').forEach(function(id) {
$('#' + id).show();
});
}
从而删除所有(损坏的)条件逻辑。