[英]Appending Hash to URL on .load() Page Update
背景 :我有一个带有如下所示标记的页面。 我正在使用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>
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('');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.