JS页面显示取决于URL

时间:2015-02-19 09:47:04

标签: javascript css hashtag

我有一个网站将所有内容加载到一个文件中,然后将所有div样式更改为display:none,而不是从菜单中选择的那个。

我想要的是能够在网址中添加一个哈希值,然后指向其中一个div并隐藏其他所有其他内容,例如点击菜单按钮时会发生的事情。

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

这是我开始添加的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");
    }
});

谢谢!

2 个答案:

答案 0 :(得分:1)

现在,您正在使用一个函数来显示和隐藏设置事件侦听器时定义的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");
  }
}

第二部分是你如何触发这个功能。您的代码有一组' if'由 $(document).ready 调用的匿名函数中的语句。 首先,因为您基本上在进行一组字符串比较,所以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);

“开关”的替代品'声明是使用字典将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语句有效,尽管可以说是更整洁。

答案 1 :(得分:0)

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

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

相关问题