2016-09-30 45 views
0

我遇到了history.js,作爲我遇到的一些問題的可能解決方案。對於我正在建設的網站,我決定創建一個靜態頁面,將內容加載到該頁面。所以我會有3個Divs,(一個用於標題,一個用於菜單欄,另一個用於內容)當點擊菜單中的鏈接時,該頁面將被加載到內容div中。因爲所有的流量都停留在index.php頁面上,所以點擊後退按鈕我會去上次訪問的內容,但上次訪問的頁面。我的理解是我可以用history.js解決這個問題。有些麻煩爲我創建的網站實施History.js

所以在我的頁面上,我有幾個鏈接在菜單欄中onclick函數被調用。例如

<li><a href="javascript:void(0);" onclick="myprofile()" ><span>my profile</span></a></li> 
    <li><a href="javascript:void(0);" onclick="mysettings()"><span>Settings<small> 

函數看起來像這樣。

function myprofile() { 
$('#content').load('members.php'); 
} 
function mysettings() { 
$('#content').load('settings.php'); 
} 

我添加了history.js一些JavaScript(在這個論壇上找到)雖然它確實改變我的index.php裏面的網址,但點擊回來時它不加載頁面。如何在使用函數時讓history.js工作? (一些鏈接我做的真的需要這樣的功能只是把在onload裏面的鏈接將不會是一種選擇對我來說)

<script> 
        $(function() { 

    // Prepare 
    var History = window.History; // Note: We are using a capital H instead of a lower h 
    if (!History.enabled) { 
     // History.js is disabled for this browser. 
     // This is because we can optionally choose to support HTML4 browsers or not. 
     return false; 
    } 

    // Bind to StateChange Event 
    History.Adapter.bind(window,'statechange',function() { // Note: We are using statechange instead of popstate 
     var State = History.getState(); 
     $('#content').load(State.url); 
     /* Instead of the line above, you could run the code below if the url returns the whole page instead of just the content (assuming it has a `#content`): 
     $.get(State.url, function(response) { 
      $('#content').html($(response).find('#content').html()); }); 
     */ 
     }); 


    // Capture all the links to push their url to the history stack and trigger the StateChange Event 
    $('a').click(function(evt) { 
     evt.preventDefault(); 
     History.pushState(null, $(this).text(), $(this).attr('onclick')); 
    }); 
}); 
</script> 
+0

你在調試器中檢查了你的javascript嗎?錯誤在哪裏?或者它開始採取不同的行動之前它在哪裏? –

+0

好吧,它將頂部欄中的地址更改爲site.com/myprofile(),這不是有效的地址 – Wouter

+0

將您的pushState調用更改爲:「History.pushState(null,$(this).text(),'成員。 PHP');」因爲第三個參數是URL,並且它看起來像是將「onclick」javascript事件添加到歷史記錄中,而不是您實際想要/需要的URL。 –

回答

1

的History.pushState的第一個參數是「數據」,這是額外的信息。閱讀它的時候回來了,你會做這在您的History.Adapter.bind功能

History.pushState({ href: 'members.php' }, $(this).text(), $(this).attr('onclick')); 

然後:

所以保存的歷史記錄條目,你可以在點擊事件做到這一點

$('#content').load(State.data.href);