我根据从另一个页面解析的查询字符串参数的内容显示隐藏的 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 为 true 后停止。所以你的代码应该看起来像
if ((urlParams["q1"]).indexOf("bag1") >= 0) {
$(".content1").show();
}
if ((urlParams["q1"]).indexOf("bag2") >= 0) {
$(".content2").show();
}
if ((urlParams["q1"]).indexOf("bag3") >= 0) {
$(".content3").show();
}
关于javascript - 对具有多个值的查询字符串参数使用 indexof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32627827/