[英]JS page display depending on URL
我有一个网站,将所有内容加载到一个文件中,然后将所有div样式更改为display:none
从菜单中选择一个)。
我想要的是能够向URL添加一个哈希,然后将其指向div之一并隐藏所有其他哈希,就像单击菜单按钮时发生的一样。
在此处查看网站以及JS,CSS和HTML: http : //jsfiddle.net/5vL2LjLe/2/
这是我开始添加以检查URL是否包含某些文本的JavaScript:
//shows page depending on url
$(document).ready(function() {
if(window.location.href.indexOf("#lgc") > -1) {
console.log("#lgc");
}
else if(window.location.href.indexOf("#webcams") > -1) {
console.log("#webcams");
}
else if(window.location.href.indexOf("#rasp") > -1) {
console.log("#rasp");
}
else if(window.location.href.indexOf("#charts") > -1) {
console.log("#charts");
}
else if(window.location.href.indexOf("#dunstablepara") > -1) {
console.log("#dunstablepara");
}
});
谢谢!
现在,您正在使用一个函数来显示和隐藏在设置事件侦听器时定义的DIV。 但是,您想要做的基本上是提名(例如,按名称)要显示或隐藏的部分具有相同的效果。
一种实现方法是创建一个可以提供ID前缀的函数,该函数将隐藏并显示页面的相关部分。 以下内容基本上是从您现有的“菜单单击器”处理程序派生的。
function switchToDiv(idprefix) {
var navItem = $('#' + idprefix + '-link'),
pageDiv = $('#' + idprefix + '-page');
if (!(navItem.hasClass('active'))) {
//hide other pages and show the linked one
$("div[id*='-page']").hide();
pageDiv.show();
//set all links inactive and the clicked on active
$("li[id*='-link']").removeClass("active");
navItem.addClass("active");
}
}
第二部分是如何触发该功能。 您的代码在$(document).ready调用的匿名函数中具有一组“ if”语句。 首先,因为您基本上是在进行一组字符串比较,所以switch语句更适合。 另外,由于您可能想在其他时间使用该函数,因此值得给它起一个名字。
function loadPageFromHash() {
switch (window.location.hash) {
case '#lgc':
switchToDiv('lgcweather');
break;
case '#rasp':
switchToDiv('rasp');
break;
case '#charts':
switchToDiv('charts');
break;
case '#dunstablepara':
switchToDiv('dunstablepara');
break;
case '#webcams':
switchToDiv('webcam');
break;
default:
// do anything you need to in order to load the home page
}
}
最后,你可以调用该函数在页面加载时,当如果是可取的URL变化的哈希值。
//shows page depending on url
$(document).ready(loadPageFromHash);
$(window).on('hashchange',loadPageFromHash);
'switch'语句的替代方法是使用字典将URL#文本映射到'prefix',例如:
function loadPageFromHash() {
var mappings = {
'#lgc': 'lgcweather',
'#rasp': 'rasp',
'#charts':'charts',
'#dunstablepara':'dunstablepara',
'#webcams':'webcam'
}
if (window.location.hash in mappings) {
switchToDiv(mappings[window.location.hash]);
} else {
//special case for home
}
}
请记住,使用上述编写的函数,每次都会创建映射字典。 尽管可以说整洁,但这肯定比switch语句效率低。
您正在寻找location.hash
而不是location.href
。
W3Schools: http : //www.w3schools.com/jsref/prop_loc_hash.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.