2016-01-20 61 views
1

我將創建一個單頁JavaScript應用程序。它會根據被修改的URL加載不同的頁面內容,或者通過哈希或者HTML歷史API取決於瀏覽器。基於散列或查詢字符串加載動態內容

我的使用plugin是爲了讓舊版瀏覽器具有散列回退功能。

var location = window.history.location || window.location; 

handleUrlChange(location.href); 

$(document).on('click', 'a.ajax', function(e) { 
    e.preventDefault(); 
    history.pushState(null, null, this.href); 
    handleUrlChange(this.href); 
}); 

$(window).on('popstate', function(e) { 
    handleUrlChange(location.href);  
}); 

function handleUrlChange(url){ 
    // example url: www.foo.com?page=details&id=1 
    var page = getQueryStringParam('page') || 'index'; 
    $('#dynamic-content').load(page + '.html'); 
} 
<!DOCTYPE html> 
<html> 
    <head> 
    <meta charset="UTF-8"> 
</head> 
    <body> 
     <div id="header"></div> 
     <div id="dynamic-content"></div> 
     <div id="footer"></div> 
    </body> 
</html> 

我的問題是,如果有一些已經這樣做了任何框架?我不想在這裏重新發明輪子。

回答

2

有很多的解決方案,如:

  1. https://millermedeiros.github.io/crossroads.js/
  2. http://stoodder.github.io/finchjs/
  3. http://backbonejs.org/#Router
  4. https://docs.angularjs.org/tutorial/step_07

你可以選擇最適合你的。如果您不想使用模型或集合等主幹功能或者角度框架,並且只需要路由,請使用crossroads.js或finch.js,或者只需鍵入google:「Javascript路由」以查找其他庫。

就我個人而言,我只使用骨幹路由。

http://backbonejs.org/#Router

它易於使用,自動檢查,如果歷史API可以被使用,如果沒有,它使用哈希導航。

+0

謝謝,我發現https://github.com/flatiron/director這看起來不錯。我是否需要下載整個骨幹庫才能使用它的路由器? – filur

+0

是的,爲了使用骨幹路由器,您需要整個骨幹庫,以及骨幹依賴的下劃線和jquery。 – SciFiThief