1

背景:我有一个带有如下标记的页面。我正在使用 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>
4

1 回答 1

2

AFAIK,纯jQuery无法做到这一点。您想要操纵浏览器历史记录以将路由添加到您的应用程序,为此您需要一个jQuery 插件,或者直接使用浏览器的原生 API:监听hashchange事件和/或 HTML5 History 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('');
  }
});
于 2013-10-31T22:35:38.940 回答