[英]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.