简体   繁体   English

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

[英]Appending Hash to URL on .load() Page Update

BACKGROUND : I've got a page with the markup shown below. 背景 :我有一个带有如下所示标记的页面。 I'm using jQuery's .load() method to replace the contents of div.content-container with this code: 我正在使用jQuery的.load()方法用以下代码替换div.content-container的内容:

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

QUESTION : The method works, but I'd like to append the URL with a hash, ie #page2, which would allow back button functionality . 问题 :该方法有效,但是我想在URL后面附加一个哈希,即#page2,该哈希将允许返回按钮功能 Is there a way to add this feature to a site based entirely on HTML and jQuery .load() ? 有没有办法将此功能完全添加到基于HTML和jQuery .load()的网站上?

I've looked at Ben Alman's BBQ plugin, but as someone new to asynchronous content and a non-expert in jQuery, I'm having trouble figuring out how to implement it in my project. 我看过Ben Alman的BBQ插件,但是作为异步内容的新手和jQuery的非专家,我在弄清楚如何在我的项目中实现它时遇到了麻烦。

HTML of main page: 主页的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 (and later pages) are not full HTML documents: page2.html(及更高版本)不是完整的HTML文档:

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

AFAIK, there is no way to do this withing pure jQuery. AFAIK, jQuery无法做到这一点。 You want to manipulate the browser history to add routing to your application, and to do this you require either a jQuery plugin , or directly with the native APIs of the browser: listening to the hashchange event and/or the HTML5 History API. 您想要操纵浏览器历史记录以向您的应用程序添加路由,并且为此需要jQuery插件或直接使用浏览器的本机API:侦听hashchange事件和/或HTML5 History API。

Quick and dirty toy example to "clear" your div : 快速而肮脏的玩具示例可以“清除” 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM