【发布时间】:2019-09-09 16:15:07
【问题描述】:
下面的代码显示和隐藏基于 URL 参数的 div。但是,URL 参数将显示多个项目,而不仅仅是一个(苹果、橙子)。使用不起作用的当前代码。它不会显示任何内容。相反,我需要它显示它是否包含“苹果”,然后显示苹果 div。如果它包括“橙子”,也显示橙子。这个超出了我的范围,我需要一些帮助来配置它。提前感谢您的帮助!
我使用的脚本如下。就像我说的,我将使用的 URL 参数将是“apples, oranges,bananas”的变体
<script type="text/javascript">
// Parse the URL parameter
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Give the parameter a variable name
var dynamicContent = getParameterByName('dc');
$(document).ready(function() {
// Check if the URL parameter is apples
if (dynamicContent == 'apples') {
$('#apples').show();
}
// Check if the URL parameter is oranges
else if (dynamicContent == 'oranges') {
$('#oranges').show();
}
// Check if the URL parameter is bananas
else if (dynamicContent == 'bananas') {
$('#bananas').show();
}
// Check if the URL parmeter is empty or not defined, display default content
else {
$('#default-content').show();
}
});
</script>
【问题讨论】:
-
为了确保我理解 - 您希望它与参数的任何值一起工作,而不是硬编码为两个或三个值,如“apples”和“oranges”?
-
您的网址是什么样的?有几种方法可以传递多个值,而在
$(document).ready函数中解决此问题的方式取决于传递值的方式。例如,您可以使用example.com/fruits?item=apple&item=orange,这不同于example.com/fruits?items=apple,orange -
我的网址如下所示:example.com?dc=apples,%20oranges
-
从网络表单中,他们将能够选择在 url 中传递的三个选项。在确认页面上,我希望为 URL 中传递的每个选项(三个选项)显示一个 div。如果他们采摘香蕉,它将显示香蕉 div。如果他们采摘了香蕉和橙子,它将显示香蕉 div 和橙子 div。如果他们摘了苹果和橙子,它将只显示苹果 div 和橙子 div。
-
更正:我的网址如下所示:example.com?dc=apples%0Aoranges
标签: javascript