2013-11-22 61 views
1

頁面範圍我已經加載從數據庫中動態內容的功能,因此當某鏈接的點擊稱爲:window.onpopstate隻影響一個

jQuery的

<script> 
function loadContent(href){ 
$.getJSON("/route", {cid: href, format: 'json'}, function(results){ 
$("#content_area").html(""); 
$("#content_area").append(results.content); 
reinitFunc1(); 
reinitFunc2(); 
reinitFunc3(); 
// history.pushState('', 'New URL: '+href, href); 
}); 
}; 
</script> 

我想要啓用pushStateonpopstate

我可以通過取消註釋上述history.pushState行來啓用URL和瀏覽器歷史更改 - 在多個頁面上向前和向後導航都可以正常工作。

但是這不加載內容。

前陣子我認爲我有充分的功能性(即導航和內容加載)與添加這些元素:

window.onpopstate = function(event) { 
console.log("pathname: "+location.pathname); 
loadContent(location.pathname); 
}; 

因此我試圖將它們添加到一個單獨的塊:

<script> 
$(document).ready(function() { 
window.onpopstate = function(event) { 
console.log("pathname: "+location.pathname); 
loadContent(location.pathname); 
}; 
}); 
</script> 

但是,這導致頁面範圍在導航時被限制爲一個,我無法向前導航。

如何使用上述代碼作爲基礎實現導航和內容加載?

編輯

以供參考,正確的路徑是在瀏覽器歷史記錄,這只是他們不能被導航(FF和Chrome)和相應的內容不加載。在Firebug中沒有錯誤。

回答

0

我想這就是答案,我碰到這樣的:

https://stackoverflow.com/a/10176315/1063287

「還要確保在onpopstate()加載頁面不要試圖推動利用 pushState的()自己」 。

所以我一直在這個:

<script> 
$(document).ready(function() { 
window.onpopstate = function(event) { 
console.log("pathname: "+location.pathname); 
loadContent(location.pathname); 
}; 
}); 
</script> 

但是從功能移除了這個:

history.pushState('', 'New URL: '+href, href); 

並補充它,而不是對jQuery觸發點擊例如:

$(document).on("click","#main_menu a", function (e) { 
href = $(this).attr("href"); 
loadContent(href); 
history.pushState('', 'New URL: '+href, href); 
e.preventDefault(); 
});