JS页面显示取决于URL

JS page display depending on URL

本文关键字:取决于 URL 显示 JS      更新时间:2024-01-12

我有一个网站,它将所有内容加载到一个文件中,然后将所有div样式更改为display:none(从菜单中选择的样式除外)。

我想要的是能够在url中添加一个散列,然后指向其中一个div并隐藏所有其他div,就像点击菜单按钮时发生的那样。

在此处查看网站以及JS、CSS和HTML:http://jsfiddle.net/5vL2LjLe/2/

这是我开始添加的JavaScript,用于检查URL是否包含特定文本:

//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#文本映射到"前缀",例如:

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

W3学校:http://www.w3schools.com/jsref/prop_loc_hash.asp