我正在尝试重新设计解决方案 http://www.randomsnippets.com/2011/10/09/how-to-hide-or-show-content-based-on-links-or-urls-via-javascript-jquery/处理我的网站,我想根据部分目录结构的名称更改一些内容。
我的目录结构如下所示,其中包含我想要根据大写字母更改内容的 URL 部分:
示例中的代码如下:
<html>
<head>
<title>Hiding and showing content based on URLs</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var option = 'coke';
var url = window.location.href;
option = url.match(/option=(.*)/)[1];
showDiv(option);
});
function showDiv(option) {
$('.boxes').hide();
$('#' + option).show();
}
</script>
<style type="text/css">
.boxes {
display: none;
}
</style>
</head>
<body>
<div class="boxes" id="coke">Coke is awesome!</div>
<div class="boxes" id="bubble-tea">Bubble tea is da bomb!</div>
<div class="boxes" id="milk">Milk is healthy!</div>
</body>
</html>
据我所知,为了使其与我的 URL 结构兼容,我需要更改的部分是:
var url = window.location.href;
option = url.match(/option=(.*)/)[1];
任何人都可以帮助我如何查找我的目录名称而不是 URL 参数吗?
最佳答案
您可以使用 array.split 获取 URL 的每个部分
var parts = window.location.pathname.split('/')
在您的示例中:http://example.com/main/MILK/content/page/
然后,你可以这样做:
console.log(parts[0]) // will be main
console.log(parts[1]) // will be MILK
console.log(parts[2]) // will be content
console.log(parts[3]) // will be page
我使用 location.path 获取域名后面的所有内容(从字符串中删除 http://exampale.com
)
您可以在一行中完成此操作,并且测试条件:
option = location.pathname.split('/')[1]
if( option=='MILK') showDiv('...')
<小时/>
更多信息:
关于javascript - 重写 javascript 以根据 URL 参数显示内容,而不是使用目录名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41590202/