实现多层次的深层链接

时间:2011-02-03 11:38:30

标签: javascript jquery

我需要为我的网站实现深层链接,因为它在AJAX中大量构建。我理解了基本的想法,并为我的顶级导航实现了深层链接。问题是我的网站有多个级别。用户可以单击顶部导航,添加到散列,然后单击辅助导航和三级导航。我还需要将此二级和三级导航单击添加到哈希...然后还能够在用户单击主导航项目时删除该项目。我想不出办法做到这一点......任何想法?

哦,我用来在主导航上实现散列的代码(jQuery)是:

updateHash : function(hash) {
    var hashHistory = [];
    location.hash = hash;
}

1 个答案:

答案 0 :(得分:2)

我不太确定你在找什么。也许你应该展示一些具体的例子。在那之前怎么样:

function updateHash(hashPath) {
   if (hashPath.charAt(0) == "/") {
     location.hash = "#" + hashPath;
     return;
   }

   var currentHash = location.hash.split(/\//);
   if (currentHash[0]) currentHash[0] = currentHash[0].substr(1); // Loose the #

   var relHash = hashPath.split(/\//);

   var part;
   while (part = relHash.shift()) {
     if (part == "..") {
        currentHash.pop();
     } else {
        currentHash.push(part);
     }
   }

   if (currentHash.length > 0)
      location.hash = "#" + currentHash.join("/");
   else
      location.hash = "";
}

示例:

updateHash("/topLevelItem");
alert(location.href); // "www.example.com/#/topLevelItem"

updateHash("secondLevelItem");
alert(location.href); // "www.example.com/#/topLevelItem/secondLevelItem"

updateHash("thirdLevelItem");
alert(location.href); // "www.example.com/#/topLevelItem/secondLevelItem/thirdLevelItem"

updateHash("../differentThirdLevelItem");
alert(location.href); // "www.example.com/#/topLevelItem/secondLevelItem/differentThirdLevelItem"

updateHash("../../differentSecondLevelItem");
alert(location.href); // "www.example.com/#/topLevelItem/differentSecondLevelItem"

updateHash("../anotherSecondLevelItem/anotherThirdLevelItem");
alert(location.href); // "www.example.com/#/topLevelItem/anotherSecondLevelItem/anotherThirdLevelItem"

updateHash("..");
alert(location.href); // "www.example.com/#/topLevelItem/anotherSecondLevelItem"