在页面加载时获取ajax哈希url



假设我在ajax调用时设置了一个哈希值:

示例:http://example.com/hash.html

如果我加载另一个页面并单击后退按钮,我将如何检测哈希并提取加载时的url ?剩下的我已经搞定了:)。

如果您需要更多代码,请告诉我。顺便说一句,我用的是jquery

您有几个选择。

最明显的是

window.location.hash;

…它已经成为实际JavaScript的一部分有些年了(更多信息在这里或通过谷歌"JavaScript位置哈希")。

还有一个jQuery插件叫做jQuery。

有一个事件,hashchange,但它只支持Firefox 3.6, IE8,我想最新的chrome和safari。

为获得最佳支持,检测hashchange事件,如果不存在,则使用setInterval()的轮询功能。

所以你可以这样做…

(function() { 
   var hash = window.location.hash;
   if ('onhashchange' in window) {
      window.onhashchange = hashChanged;
   } else {
      setInterval(function() {
         if (window.location.hash != hash) {
             hash = window.location.hash;
             hashChanged();
         }
      }, 500);
   }
   var hashChanged = function() {
     alert('Hash has changed!');
   };
})();
$(function() {
   var page = window.location.hash;
   if (page == "") page = "somedefaultpage.html";
   $("#content").load(page);
});

如果你已经正确地连接了你的导航页面加载到你的内容元素应该已经在那里了因为浏览器必须导航到#hash

一个简单的例子,使用window.location.hash在url中加载适当的散列内容,同时来回导航。

希望这对某人有所帮助…干杯!!

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
    a{
        text-decoration: none;
        color:#999;
        font: arial;
    }
    .content{
        width: 50%;
        height: 30px;
        border:1px solid darkorange;
        padding: 3%;color:#999;
    }
</style>

<body>
<div class="box">
<a id="hash1" href="">Add Hash1</a>
<a id="hash2" href="">Add Hash2</a>
</div>
<div class="content"></div>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
    $(".box a").click(function(e) {
        window.location.hash = $(this).attr("id");
        e.preventDefault();
    });
$(window).on('hashchange', function() {
  if (location.hash === '#hash1') {
    $("div.content").html('Hash one added!');
  }
  if (location.hash === '#hash2') {
    $("div.content").html('Hash two added!');
  }
  if (location.hash === '') {
    $("div.content").html('');
  }
});
});
</script>
</body>
</html>

最新更新