JS页面显示依赖URL

JS page display depending on URL

我有一个网站将所有内容加载到一个文件中,然后将所有 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");
    }
});

谢谢!

您正在寻找 location.hash 而不是 location.href

W3Schools:http://www.w3schools.com/jsref/prop_loc_hash.asp

现在,您正在使用一个函数来显示和隐藏在设置事件侦听器时定义的 DIV。但是,您想要做的基本上与指定(例如按名称)要显示或隐藏的部分具有相同的效果。

一种方法是创建一个函数,您可以在其中提供 ID 前缀,它会隐藏和显示页面的相关部分。以下内容基本上来自您现有的 'menu-clicker' 处理程序。

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 语句效率低,尽管可以说更整洁。