Javascript 如何实现哈希键导航?
我想实现一个基于Ajax的哈希键导航,如下所示:Javascript 如何实现哈希键导航?,javascript,navigation,Javascript,Navigation,我想实现一个基于Ajax的哈希键导航,如下所示: http://www.foo.bar/#/about/ http://www.foo.bar/#/news/ http://www.foo.bar/#/products/ 如何实现此结构?使用基于哈希的导航结构,您将通过浏览器中的JS定义路由及其处理程序。。。更改哈希时,将触发“hashchange”事件,并调用“window.onhashchange”处理程序函数* e、 g 也可以选择使用最近推出的HTML5 pushstate 查看一些好
http://www.foo.bar/#/about/
http://www.foo.bar/#/news/
http://www.foo.bar/#/products/
如何实现此结构?使用基于哈希的导航结构,您将通过浏览器中的JS定义路由及其处理程序。。。更改哈希时,将触发“hashchange”事件,并调用“window.onhashchange”处理程序函数* e、 g 也可以选择使用最近推出的HTML5 pushstate 查看一些好的JS路由库——其中一些提供了对HTML5 pushstate的支持,以及对旧浏览器的hashchange的回退 如果你想构建一个严肃的应用程序,你可以使用像Backbone.js这样的东西来处理模型、视图、路由等等。如果你不需要Backbone附带的所有额外功能,你还应该查看Crossroads.js(路由库)及其附带的Hasher.js(hashchange/pushstate库) …或者存在路由(仅限HTML5 pushstate,非常类似于Express for Node.js中的路由) …或Jquery BBQ(用于Jquery/hashchange-based/一些不错的特性--(github.com/cowboy/Jquery BBQ) …还有Director(hashchange/tons of features/works in Node.js和浏览器/类似于Express routing/主要由Nodejitsu的人员开发) *注意:如果你专注于SEO,那么hashchange/ajax会带来一些问题……你可能需要阅读谷歌网站管理员指南--
**另外,你可以在MicroJS.com网站上找到上面提到的所有库,除了Jquery BBQ,使用上面给出的示例,为了简单起见,你可以执行以下操作:
function aboutHandler() {
//Do stuff--e.g. get via AJAX -> render template (optional) -> append HTML to an element
}
function newsHandler() {
//Do stuff
}
function productsHandler() {
//Do stuff
}
function locationHashChanged() {
(location.hash === "#/about/") && aboutHandler();
(location.hash === "#/news/") && newsHandler();
(location.hash === "#/products/") && productsHandler();
}
}
window.onhashchange = locationHashChanged;
看起来您正在开发一个单页应用程序。因此,我建议您使用。以下是用于您的任务的代码片段
<script>
var Controller = Backbone.Router.extend({
routes: {
"/about/": "about",
"/news/": "news",
"/products/": "products"
},
about: function(){
// ...
},
news: function(){
// ...
},
products: functions(){
// ...
}
});
var controller = new Controller();
Backbone.history.start();
</script>
var控制器=主干网.Router.extend({
路线:{
“/about/”:“about”,
“/news/”:“news”,
“/products/”:“products”
},
关于:函数(){
// ...
},
新闻:功能(){
// ...
},
产品:功能(){
// ...
}
});
var控制器=新控制器();
Backbone.history.start();
这个问题可能会因为不是真正的问题而被关闭。你能更清楚地说明你有什么问题吗?试试sammyjs
<script>
var Controller = Backbone.Router.extend({
routes: {
"/about/": "about",
"/news/": "news",
"/products/": "products"
},
about: function(){
// ...
},
news: function(){
// ...
},
products: functions(){
// ...
}
});
var controller = new Controller();
Backbone.history.start();
</script>