[英]History API with jQuery - address bar changes but doesn't refresh divs
我已經能夠輕松地使用history.pushState更改div的內容,並使地址欄反映一個偽造的url。 但是,每當我按下“后退/前進”按鈕時,URL都會變回原先的位置,但內容保持不變。 在URL中輸入錯誤。 看來我的歷史記錄API的第一部分已關閉,但需要幫助進行狀態更改。
我是一個相當新的程序員,並且嘗試在jQuery中構建我的網站並盡可能簡化代碼。
HTML代碼:
<ul>
<li><button class="navButton" id="signUp" href="./content/registration.php" name="registration" title="Registration">Sign Up</button></li>
<li><button class="navButton" id="settings" href="./content/account_settings.php" name="settings" title="settings">Settings</button></li>
<li><button class="navButton" id="about" href="./content/about.php" name="about" title="About">About</button></li>
</ul>
<div id="mainContent"></div>
JavaScript代碼:
$(document).ready(function() {
// INITIAL CONTENT ON FIRST LOAD
$("#mainContent").load('./content/start.php');
// CODE FROM HISTORY.JS
(function(window, undefined) {
var History = window.History;
if (!History.enabled) {
return false;
}
History.Adapter.bind(window, 'statechange', function() {
var State = History.getState();
History.log(State.data, State.title, State.url);
});
// EVENT LISTENER FOR NAVBUTTON CLASS TO REPLACE CONTENT IN MAINCONTENT DIV
$('.navButton').click(function(e) {
e.preventDefault();
pageurl = $(this).attr('name');
$("#mainContent").fadeOut().load($(this).attr("href")).fadeIn();
if (pageurl != window.location) {
history.pushState('', $(this).attr('title'), $(this).attr('name'));
}
});
})(window);
});
我已經安裝了history.js,但是如果我不需要使用它,那將是首選。 我希望糾正此代碼,以便后退按鈕刷新,並且可以正常工作!
因此,我通過在popstate下添加一個if語句來比較此URL,並確定在mainContent div中加載的內容來解決此問題。 工作! 該問題已發布找不到我在哪里有創建多個歷史記錄條目的popstate循環
window.addEventListener('popstate', function() {
//WHEN BACK/FORWARD CLICKED CHECKS URL PATHNAME TO DETERMINE WHICH CONTENT TO PLACE IN DIV
if (location.pathname == "/index.php") {
$("#mainContent").load("./content/start.php");
} else {
$("#mainContent").load("./content" + location.pathname + ".php");
}
});
建議:使用內置的html5歷史記錄狀態,以傳遞對象或參數等。
將狀態推入瀏覽器時的操作:
history.pushState('{url:location}', $(this).attr('title'), $(this).attr('name'));
使用瀏覽器向后或向前單擊時的操作:
$(window).on('popstate', function(e){
if(e.originalEvent.state != null){
console.log("url to render"+e.originalEvent.state.url)
}else{
console.log("nothing in the state, do nothing")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.