在.load()页面更新上将哈希附加到URL

时间:2013-10-31 19:42:43

标签: jquery asynchronous jquery-bbq

背景:我有一个带有如下标记的页面。我正在使用jQuery的.load()方法用这段代码替换div.content-container的内容:

$(document).on('click', 'button#page2', function() {
   $("div.content-container").load("page2.html");
});

问题:该方法有效,但我想用一个哈希值附加一个URL,即#page2,这将允许后退按钮功能。有没有办法将此功能完全基于HTML和jQuery .load()添加到网站?

我看过Ben Alman的BBQ插件,但作为异步内容的新手和jQuery的非专家,我无法弄清楚如何在我的项目中实现它。

主页的HTML:

<head>
<!--scripts & styles-->
</head>
<body>
<button id="page2">Page 2</button>
<button id="page3">Page 3</button>
<div class="content-container">
<!--content is loaded here-->
</div>
</body>

page2.html(及更高版本的网页)不是完整的HTML文档:

<p>Here's some content from the second page.</p>

1 个答案:

答案 0 :(得分:2)

AFAIK,使用 pure jQuery无法做到这一点。您希望操纵浏览器历史记录以向您的应用程序添加路由,要执行此操作,您需要jQuery plugin或直接使用浏览器的本机API:收听hashchange事件和/或HTML5历史API。

快速而肮脏的玩具示例,以“清除”您的div

$(document).on('click', 'button#page2', function() {
   $("div.content-container").load("page2.html");
   location.hash = '#page2';
});

$(window).on('hashchange', function() {
  if (location.hash === '') {
    $("div.content-container").html('');
  }
});
相关问题