AJAX导航
$.mobile.navigate
方法和navigate
事件表单是jQuery Mobile的导航基础。因此,他们可以在jQuery Mobile的作用范围之外,作为一种清洁和直观的导航/历史的API运作。
简介
jQuery Mobile包括一个通过AJAX加载页面到DOM,增强页面新内容,并且显示一组丰富的过渡动画的网页的导航系统。该导航系统采用渐进式增强自动'劫持'的标准链接和表单提交,并将它们作为一个AJAX请求路由。
jQuery Mobile的核心特性之一是能够像锚和后退按钮一样加载和显示来自不同页面的内容至支持标准导航方法的初始化文档。要做到这一点,jQuery Mobile需要渐进地提供hashchange
和popstate
配上可单点内部历史记录跟踪的支持。
Twitter的Web客户端就是一个不错的示例用例。第一步是在网页上劫持点击,通过URL表示$.mobile.navigate
跟踪历史的UI状态。在这一点上,任何关于使用后退按钮返回操作所需的UI附加信息将被保存。(见导航方法的对象参数的foo
属性)
// Define a click binding for all anchors in the page
$( "a" ).on( "click", function( event ){
// Prevent the usual navigation behavior
event.preventDefault();
// Alter the url according to the anchor's href attribute, and
// store the data-foo attribute information with the url
$.mobile.navigate( this.attr( "href" ), {
foo: this.attr("data-foo")
});
// Hypothetical content alteration based on the url. E.g, make
// an AJAX request for JSON data and render a template into the page.
alterContent( this.attr("href") );
});
下一步,navigate
事件绑定有助于通过浏览器历史API实现向后和向前导航。alterContent
函数可以记录浏览器导航的方向,以及当$.mobile.navigate
被调用储存相应的历史记录条目时,把任何其他信息存储为数据对象。
// Respond to back/forward navigation
$( window ).on( "navigate", function( event, data ){
if( data.state.foo ){
// Make use of the arbitrary data stored
}
if( data.state.direction == "back" ) {
// Make use of the directional information
}
// reset the content based on the url
alterContent( data.state.url );
});
事件示例
jQuery Mobile提供navigate
事件作为hashchange
和popstate
的包装。也就是说,在一个是否支持popstate的浏览器上绑定两个事件时,只需绑定一个navigate
事件即可。在这个示例中,在不同的浏览器下,改变哈希值会触发popstate
或hashchange
事件,在这里只需绑定一个navigate
事件。请务必在改变哈希值后使用后退按钮,以致于可以看到在这个两种情况下都会触发事件。
注意:当查看控制台输出时,有些浏览器(例如:Chrome)会在初始化页面加载时触发popstate事件
// Bind to the navigate event
$( window ).on( "navigate", function() {
console.log( "navigated!" );
});
// Bind to the click of the example link
$( "#event-example" ).click(function( event ) {
event.preventDefault();
location.hash = "foo";
});
事件示例
方法示例
jQuery Mobile提供$.mobile.navigate
方法作为跟踪历史记录和接收伴随着navigate
事件的其他信息。在这个示例中,但方法示例链接被点击时,URL会更改两次。第一次是通过该方法存储伴随着URL的其他任意的信息和哈希值,第二次是简单地改变URL及存储URL和哈希值。当浏览器向后移动至历史记录时,navigate
事件被触发。在上面的事件示例中,随着而来的是对历史导向的遍历,URL,哈希值和导航方法第一次调用所存储的任意数据。
注意:任意状态的属性必须被小心选择,以避免与URL,哈希和导航属性冲突。在未来的版本中将会解决这个问题。
// Bind to the click of the example link
$( "#method-example" ).click(function( event ) {
// Append #bar
$.mobile.navigate( "#bar", {
info: "info about the #bar hash"
});
// Replace #bar with #baz
$.mobile.navigate( "#baz" );
// Log the results of the navigate event
$( window ).on( "navigate", function( event, data ){
console.log( data.state.info );
console.log( data.state.direction );
console.log( data.state.url );
console.log( data.state.hash );
});
// Go back to pop the state for #bar and log it
window.history.back();
});
方法示例