我有一個頁面,其左側的導航鏈接和右側的內容div。導航鏈接HTML是這樣設置的。爲AJAX加載的內容操縱瀏覽器歷史記錄
<a href="javascript:;" class="nav-link" data-mode="myModeValue">Test</a>
我已成立了一個JavaScript函數,如下面看到的,我認爲會綁定到的聯繫,推動一個新的狀態到瀏覽器歷史記錄,並加載了基於數據模式的值鏈接的內容。向前走可以完美運行,但是當我向後退時,我必須點擊兩次才能回到之前的散列,我不知道爲什麼。
這是我到目前爲止。
<script language="javascript">
// Create var indicating the CURRENT mode we're on - home being the default when page loads
currentMode = "home";
// Push the default page (mode) into the history
history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + currentMode);
// bind to my nav links
$(document).on('click', '.nav-link', function(e){
e.preventDefault();
ajaxLoadVehicleSearchDetailContent($(this).data('mode'));
});
function ajaxLoadVehicleSearchDetailContent(mode) {
// Get the mode and link object
var thisMode = mode.toString().toLowerCase();
var thisLink = $('a[data-mode="' + mode + '"]');
// If we're switching to a different tab - continue
if (currentMode != thisMode) {
currentMode = thisMode;
// Get the content via AJAX
$.ajax({
url: "/myAjaxFunctionFileURL",
type: "POST",
data: { method:"getTabContent", mode:thisMode },
success: function(result) {
history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode);
// Update the content area - fadeOut,replace,fadeIn
$('#contentArea').fadeOut(globalAnimationDuration, function() {
$('#contentArea').html(result).fadeIn(globalAnimationDuration);
$('.nav-link').removeClass('current');
thisLink.addClass('current');
});
}
});
}
}
// Listen for the popstate and load correct content when user goes BACK in history
window.addEventListener("popstate", function() {
if (location.hash.indexOf("#!") != -1) {
var thisMode = location.hash.split("/").slice(-1)[0];
ajaxLoadVehicleSearchDetailContent(thisMode);
}
}, false);
</script>
的globalAnimationDuration
變種是簡單地用的500值的變量
任何人都可以照一些輕到爲什麼要回來的時候奇怪的行爲?甚至是一個很好的例子,展示如何執行我可以遵循的任務並相應地更新我的方法?
謝謝!
盲猜:也許如果你點擊按鈕的速度太快,兩個請求被觸發,所以推狀態發生兩次相同?你應該''console.log'所有的pushstate,看看是否會發生。如果是這樣,只需禁用向後/ froward按鈕,直到過程結束(無論ajaxRequest是成功還是失敗!) – Walfrat
找出它。這是我的邏輯錯誤。回答如下。 – Phil