本文介绍了jQuery Mobile:文档准备与页面事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在使用jQuery Mobile,并且无法理解传统文档就绪和jQuery Mobile页面事件之间的差异。 真正的区别是什么? 为什么要 < ! - 语言:lang-js - > $(document).ready(){ }); 胜过 $(document).on('pageinit'){ }); 当您从一个页面切换到另一个页面时,页面事件的顺序如何? 如何将数据从一个页面发送到另一个页面,是否可以访问上一页中的数据? 解决方案 jQuery Mobile 1.4 Update: 对于旧的页面处理方式,基本上都是jQuery Mobile 1.4之前的一切。旧的处理方式现在已被弃用,它将保持活跃,直到(包括)jQuery Mobile 1.5,所以你仍然可以使用下面提到的所有东西,至少在明年和jQuery Mobile 1.6之前。 旧的事件(包括 pageinit )不再存在,它们被替换为 pagecontainer 小部件。 Pageinit 已完全清除,您可以使用 pagecreate 替代,该事件保持不变并且不会更改。 如果您对页面事件处理的新方式感兴趣,请查看 这里 ,在任何其他情况下请随时继续阅读本文。即使你使用jQuery Mobile 1.4 +,你也应该阅读这个答案,它不仅仅是页面事件,所以你可能会发现很多有用的信息。 老年人内容: 本文也可以作为我的博客的一部分 HERE 。 $(document).on(' pageinit') vs $(document).ready() 你在 jQuery 中学习的是调用 $(document).ready() 函数中的代码,只要DOM被加载。但是,在 jQuery Mobile 中,Ajax用于在导航时将每个页面的内容加载到DOM中。因为 $(文档).ready() 将在加载第一页之前触发,并且每个用于页面操作的代码都将在执行之后执行刷新页面。这可能是一个非常微妙的错误。在某些系统上,它看起来可能正常工作,但在其他系统上可能会导致不稳定,难以重复发生。 经典jQuery语法: $(document).ready(function(){ }); 解决这个问题(相信我这是一个问题) jQuery Mobile 开发者创建页面事件。简而言之,事件是在特定页面执行中触发的事件。其中一个页面事件是 pageinit 事件,我们可以像这样使用它: $(文件).on('pageinit',function(){ }); 我们可以更进一步,使用页面id而不是文档选择器。假设我们有jQuery Mobile页面,其id为 index : < div data-role = pageid =index> < div data-theme =adata-role =header> < h3> 第一页< / h3> < a href =#secondclass =ui-btn-right> Next< / a> < / div> < div data-role =content> < a href =#data-role =buttonid =test-button>测试按钮< / a> < / div> < div data-theme =adata-role =footerdata-position =fixed> < / div> < / div> 要执行仅可用于索引页的代码,我们可以使用以下语法: $('#index')。on('pageinit',function(){ }); Pageinit 事件将在每次页面即将被加载时执行,第一次显示。除非手动刷新页面或关闭Ajax页面加载,否则不会再次触发。如果您希望每次访问页面时执行代码,最好使用 pagebeforeshow 事件。 下面是一个工作示例: http://jsfiddle.net/Gajotres/Q3Usv/ 来证明这个问题。 关于这个问题的几点说明。无论您是使用1个HTML多页还是多个HTML文件范例,建议将您的所有自定义JavaScript页面处理分隔为一个单独的JavaScript文件。这将使您的代码更好,但您将获得更好的代码概述,尤其是在创建 jQuery Mobile 应用程序时。 还有另一个特殊的 jQuery Mobile 事件,它被称为 mobileinit 。当 jQuery Mobile 启动时,它会在文档对象上触发 mobileinit 事件。要覆盖默认设置,请将它们绑定到 mobileinit 。 mobileinit 用法的一个很好的例子是关闭Ajax页面加载或更改默认的Ajax加载器行为。 $(document).on(mobileinit,function(){ // apply覆盖这里}); 页面事件转换顺序 可在此处找到活动: http://api.jquerymobile.com/category/events/ 假设我们有一个页面A和一个页面B,这是一个卸载/加载顺序: 第B页 - 活动 pagebeforecreate pagecreate page B - event pageinit api.jquerymobile.com/pagebeforehide/\"rel =noreferrer> pagebeforehide 第A页 - 活动 com / pagehide /rel =noreferrer> pagehide pagebeforeshow page B - event pageshow ol> 为了更好的页面活动理解,请阅读: pagebeforeload , pageload 和 pagebeforechange pageloadfailed > , pagechange 和 pagechangefailed 页面更改事件。这些事件在用户在应用程序页面之间导航时触发。 > pagebeforehide , pageshow 和 pagehide 是页面转换事件。这些事件在转换之前,转换过程中和转换之后被触发并被命名。 > pagecreate 和 pageinit 用于页面初始化。 pageremove 可以被触发,然后在从DOM中移除页面时处理 页面加载jsFiddle示例: http:// jsfiddle。 net / Gajotres / QGnft / 防止页面转换 如果由于某种原因需要阻止页面转换,它可以用这段代码完成: $(document).on('pagebeforechange',function(e,data){ var to = data.toPage, from = data.options.fromPage; if(typeof to ==='string'){ var u = $ .mobile.path.parseUrl(to); to = u.hash || '#'+ u.pathname.substring(1); if(from)from ='#'+ from.attr('id'); if(from ==='#index&& to ==='#second'){ alert('无法从#index转换为#second!' ); e.preventDefault(); e.stopPropagation(); //删除按钮上的活动状态,如果使用按钮触发转换 $ .mobile.activePage.find('。ui-btn-active')。removeClass('ui -btn-active ui-focus ui-btn');; } } }); 这个例子无论如何都会起作用,因为它会在每个页面转换的乞讨时触发,什么是最重要的是它可以防止在页面转换发生之前更换页面。 以下是一个可用的示例: 事件绑定/触发 jQuery Mobile 以与传统Web应用程序不同的方式工作。根据您在每次访问某个页面时设法绑定事件的方式,它会反复绑定事件。这不是一个错误,它只是 jQuery Mobile 处理页面的方式。例如,看看这个代码片段: $(document).on('pagebeforeshow','#index' ,函数(e,数据){ $(document).on('click','#test-button',function(e){ alert('Button click'); }); }); 工作jsFiddle示例: http://jsfiddle.net/Gajotres/CCfL4/ 每次访问页面 #index 点击事件将会被绑定到按钮#test-button 。通过从第1页移动到第2页并回几次来测试它。有几种方法可以防止此问题: 解决方案1 最好的解决方案是使用 pageinit 绑定事件。如果你看看官方文档,你会发现 pageinit 只会触发一次,就像文档准备好一样,所以没有办法将事件将再次受到约束。这是最好的解决方案,因为您没有像使用off方法移除事件一样的处理开销。 工作jsFiddle示例: http://jsfiddle.net/Gajotres/AAFH8/ 此工作解决方案是在一个以前有问题的例子的基础。 解决方案2 在绑定它之前移除事件: $(document).on('pagebeforeshow','#index',function(){ $(document)。 off('click','#test-button')。on('click','#test-button',function(e){ alert('Button click'); }) ; }); 工作jsFiddle示例: http://jsfiddle.net/Gajotres/K8YmG/ 解决方案3 使用jQuery Filter选择器,如下所示: $('#carousel div:Event(!click) ').each(function(){ //如果click没有绑定到#carousel div做某事}); 因为事件过滤器不是官方jQuery框架的一部分,所以可以在这里找到: http://www.codenothing.com/archives/2009/event-filter/ 简而言之,如果速度是您最关心的问题,那么解决方案2 比解决方案1好得多。 解决方案4 一个新的,可能是其中最简单的一个。 $(document).on('pagebeforeshow','#index',function(){ $(document).on('click','#test-button',function (e){ if(e.handled!== true)//这将防止事件触发多次 { alert('Clicked'); e。处理=真; } }); }); 工作jsFiddle示例: http://jsfiddle.net/Gajotres/Yerv9/ sholsinger 为此解决方案: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/ pageChange事件怪癖 - 两次触发 有时pagechange事件可以触发两次,它没有与之前提到的问题有关。 pagebeforechange事件发生两次的原因是由于toPage不是jQuery增强型DOM对象时changePage中的递归调用。这种递归是危险的,因为开发者被允许在事件中改变toPage。如果开发人员在pagebeforechange事件处理程序中始终将toPage设置为字符串,则无论该对象是否为对象,都将导致无限递归循环。页面加载事件将新页面作为数据对象的页面属性传递(应将其添加到文档中,但目前未列出)。因此,pageload事件可用于访问已加载的页面。 简而言之,这是因为您通过pageChange发送其他参数。 $ b $ $ b < a data-role =buttondata-icon =arrow -rdata-iconpos =righthref =#care-plan-view?id = 9e273f31-2672-47fd-9baa-6c35f093a800& amp; amp; name = Sat>< h3> Sat< / h3>< ; / A> 要解决此问题,请使用页面事件转换顺序中列出的任何页面事件。 页面更改时间 如上所述,当您从一个jQuery Mobile页面更改为另一个页面时,通常要么通过单击指向DOM中已存在的另一个jQuery Mobile页面的链接,或者通过手动调用$ .mobile.changePage,可以发生多个事件和后续操作。在较高级别,会发生以下操作: 页面更改过程已开始 新的页面已加载 该页面的内容是增强型(样式化) 从现有页面转换(幻灯片/ pop / etc)发生新页面 这是一个平均页面转换基准: 网页加载和处理: 3毫秒 页面加强: 45 ms 转换: 604 ms 总时间: 670 ms *这些值以毫秒为单位。 因此,您可以看到转换事件正在执行几乎90%的执行时间。 / p> 页面转换之间的数据/参数操作 可以从一个页面发送一个参数到另一个页面在页面转换期间。它可以用几种方法完成。 参考: https:// stackoverflow .com / a / 13932240/1848600 解决方案1: 您可以通过changePage传递值: $。mobile.changePage('page2.html',{dataUrl:page2 .html?paremeter = 123,data:{'paremeter':'123'},reloadPage:true,changeHash:true}); 然后读取它们: $(document).on('pagebeforeshow',#index,function(event,data){ var parameter = $(this).data(url) .split(?)[1] ;; parameter = parameters.replace(parameter =,); alert(parameter); }); 示例: index.html <!DOCTYPE html> < HTML> < HEAD> < meta charset =utf-8/> < meta name =viewportcontent =widdiv = device-widdiv,initial-scale = 1.0,maximum-scale = 1.0,user-scalable = no/> < meta name =apple-mobile-web-app-capablecontent =yes/> < meta name =apple-mobile-web-app-status-bar-stylecontent =black/> <标题> < /标题> < link rel =stylesheethref =http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css/> < script src =http://www.dragan-gaic.info/js/jquery-1.8.2.min.js> < /脚本> < script src =http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js>< / script> <脚本> $(document).on('pagebeforeshow',#index,function(){$(document).on('click',#changePage,function(){$ .mobile.changePage('second.html ',{dataUrl:second.html?paremeter = 123,data:{'paremeter':'123'},reloadPage:false,changeHash:true});});}); $(document).on('pagebeforeshow',#second,function(){var parameters = $(this).data(url)。split(?)[1] ;; parameter = parameters。 replace(parameter =,); alert(parameter);}); < /脚本> < /头> <身体GT; <! - 主页 - > < div data-role =pageid =index> < div data-role =header> < H3>第一页< / h3> < / DIV> < div data-role =content> < a data-role =buttonid =changePage> Test< / a> < / DIV> <! - 内容 - > < / DIV><! - 页面 - > < / body>< / html> b $ b second.html $ b <!DOCTYPE html> < HTML> < HEAD> < meta charset =utf-8/> < meta name =viewportcontent =widdiv = device-widdiv,initial-scale = 1.0,maximum-scale = 1.0,user-scalable = no/> < meta name =apple-mobile-web-app-capablecontent =yes/> < meta name =apple-mobile-web-app-status-bar-stylecontent =black/> <标题> < /标题> < link rel =stylesheethref =http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css/> < script src =http://www.dragan-gaic.info/js/jquery-1.8.2.min.js> < /脚本> < script src =http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js>< / script> < /头> <身体GT; <! - 主页 - > < div data-role =pageid =second> < div data-role =header> < H3>第二页< / h3> < / DIV> < div data-role =content> < / DIV> <! - 内容 - > < / DIV><! - 页面 - > < / body>< / html> b $ b 解决方案2: 或者您可以创建一个用于存储目的的持久JavaScript对象。只要Ajax用于页面加载(并且不以任何方式重新加载页面),该对象将保持活动状态。 var storeObject = { firstname:'',姓氏:''} 例如: http://jsfiddle.net/Gajotres/9KKbx/ 解决方案3:您还可以像上面一样访问上一页中的数据: $(document).on('pagebeforeshow','#index',function(e,data){ alert( data.prevPage.attr('id')); }); prevPage 对象拥有完整的上一页。 解决方案4: 作为最后一个解决方案,我们有一个漂亮的localStorage HTML实现。它只适用于HTML5浏览器(包括Android和iOS浏览器),但所有存储的数据都是通过页面刷新持久保存的。 if(typeof (存储)!==未定义){ localStorage.firstname =Dragan; localStorage.lastname =Gaic; } 示例: http://jsfiddle.net/Gajotres/J9NTr/ 可能是最佳解决方案,但在某些方面会失败iOS版本5.X。这是一个众所周知的错误。 不要使用 .live() / .bind() / .delegate() 我忘了提及tnx andleer 提醒我)使用on / off进行事件绑定/解除绑定,live / die和bind / unbind都被弃用。 jQuery的.live()方法在1.3版中引入API时被视为天赐良机。在一个典型的jQuery应用程序中,可能会有很多DOM操作,随着元素的出入,它可能变得非常繁琐。 .live()方法可以根据应用程序在应用程序的生命周期中挂钩事件。很好吗?错误的是, .live()方法非常慢。 .live()方法实际上将其事件挂接到文档对象,这意味着事件必须从生成事件的元素冒出,直到它到达文档。这可能非常费时。 现在已弃用。 jQuery团队中的人不再推荐它的使用,我也不会这样做。尽管挂钩和解除挂钩事件可能非常繁琐,但如果没有 .live() 而不是 .live() 你应该使用 .on() 。 .on() 比 .live()快2-3倍。看看这个绑定事件的基准: http://jsperf.com/ jquery-live-vs-delegate-vs-on / 34 ,一切都将从此清除。 标杆管理: 页面事件基准测试有一个很好的脚本。它可以在这里找到: https:// github .COM / jQuery的/ jQuery的移动/ BLOB /主/工具/换页-time.js 。但是在你做任何事情之前,我建议你删除它的 alert 通知系统(每个更改页面都会显示你的数据停止应用程序)并将其更改为 console.log 函数。 基本上这个脚本会记录你所有的页面事件,如果你仔细阅读这篇文章(页面事件描述),你就会知道jQm花了多少时间来处理页面增强,页面转换...... 最终笔记 总是,我的意思是始终阅读官方的 jQuery Mobile 文档。它通常会为您提供所需的信息,与其他文档不同的是,这个版本相当不错,有足够的解释和代码示例。 更改: 30.01.2013 - 增加了多重事件触发预防的新方法 31.01.2013 - 为章节添加了更好的说明页面转换之间的数据/参数操作 03.02.2013 - 为页面转换之间的数据/参数操作章节添加新内容/示例 22.05.2013 - 增加了一个页面转换/更改预防的解决方案,并添加了官方页面事件API文档的链接 18.05.2013 - 针对多个事件绑定添加了另一个解决方案 I am using jQuery Mobile, and I am having trouble understanding differences between classic document ready and jQuery Mobile page events.What is the real difference?Why should<!-- language: lang-js -->$(document).ready() {});be better than$(document).on('pageinit') {});What is the order of page events, when you transition from one page to another?How can I send data from one page to another and is it possible to access data from previous page? 解决方案 jQuery Mobile 1.4 Update:My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.Older content:This article can also be found as a part of my blog HERE.$(document).on('pageinit') vs $(document).ready()The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.Classic jQuery syntax:$(document).ready(function() {});To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:$(document).on('pageinit', function() {});We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:<div data-role="page" id="index"> <div data-theme="a" data-role="header"> <h3> First Page </h3> <a href="#second" class="ui-btn-right">Next</a> </div> <div data-role="content"> <a href="#" data-role="button" id="test-button">Test button</a> </div> <div data-theme="a" data-role="footer" data-position="fixed"> </div></div>To execute code that will only available to the index page we could use this syntax:$('#index').on('pageinit', function() {});Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.$(document).on("mobileinit", function(){ //apply overrides here});Page events transition orderFirst all events can be found here: http://api.jquerymobile.com/category/events/Lets say we have a page A and a page B, this is a unload/load order:page B - event pagebeforecreatepage B - event pagecreatepage B - event pageinitpage A - event pagebeforehidepage A - event pageremovepage A - event pagehidepage B - event pagebeforeshowpage B - event pageshowFor better page events understanding read this:pagebeforeload, pageload and pageloadfailed are fired when an external page is loadedpagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.pagebeforecreate, pagecreate and pageinit are for page initialization.pageremove can be fired and then handled when a page is removed from the DOMPage loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/Prevent page transitionIf for some reason page transition needs to be prevented on some condition it can be done with this code:$(document).on('pagebeforechange', function(e, data){ var to = data.toPage, from = data.options.fromPage; if (typeof to === 'string') { var u = $.mobile.path.parseUrl(to); to = u.hash || '#' + u.pathname.substring(1); if (from) from = '#' + from.attr('id'); if (from === '#index' && to === '#second') { alert('Can not transition from #index to #second!'); e.preventDefault(); e.stopPropagation(); // remove active status on a button, if transition was triggered with a button $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');; } }});This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.Here's a working example:Prevent multiple event binding/triggeringjQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:$(document).on('pagebeforeshow','#index' ,function(e,data){ $(document).on('click', '#test-button',function(e) { alert('Button click'); });});Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:Solution 1Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/This working solution is made on a basis of a previous problematic example.Solution 2Remove event before you bind it:$(document).on('pagebeforeshow', '#index', function(){ $(document).off('click', '#test-button').on('click', '#test-button',function(e) { alert('Button click'); });});Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/Solution 3Use a jQuery Filter selector, like this:$('#carousel div:Event(!click)').each(function(){ //If click is not bind to #carousel div do something});Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.Solution 4A new one, probably an easiest of them all.$(document).on('pagebeforeshow', '#index', function(){ $(document).on('click', '#test-button',function(e) { if(e.handled !== true) // This will prevent event triggering more than once { alert('Clicked'); e.handled = true; } });});Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/pageChange event quirks - triggering twiceSometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.In few words this is happening because you are sending additional parameters through pageChange.Example:<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&name=Sat"><h3>Sat</h3></a>To fix this problem use any page event listed in Page events transition order.Page Change TimesAs mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:A page change process is begunA new page is loadedThe content for that page is "enhanced" (styled)A transition (slide/pop/etc) from the existing page to the new page occursThis is a average page transition benchmark:Page load and processing: 3 msPage enhance: 45 msTransition: 604 msTotal time: 670 ms *These values are in milliseconds.So as you can see a transition event is eating almost 90% of execution time.Data/Parameters manipulation between page transitionsIt is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.Reference: https://stackoverflow.com/a/13932240/1848600Solution 1:You can pass values with changePage:$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });And read them like this:$(document).on('pagebeforeshow', "#index", function (event, data) { var parameters = $(this).data("url").split("?")[1];; parameter = parameters.replace("parameter=",""); alert(parameter);});Example:index.html<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <title> </title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"> </script> <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> <script> $(document).on('pagebeforeshow', "#index",function () { $(document).on('click', "#changePage",function () { $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true }); }); }); $(document).on('pagebeforeshow', "#second",function () { var parameters = $(this).data("url").split("?")[1];; parameter = parameters.replace("parameter=",""); alert(parameter); }); </script> </head> <body> <!-- Home --> <div data-role="page" id="index"> <div data-role="header"> <h3> First Page </h3> </div> <div data-role="content"> <a data-role="button" id="changePage">Test</a> </div> <!--content--> </div><!--page--> </body></html>second.html<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <title> </title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"> </script> <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> </head> <body> <!-- Home --> <div data-role="page" id="second"> <div data-role="header"> <h3> Second Page </h3> </div> <div data-role="content"> </div> <!--content--> </div><!--page--> </body></html>Solution 2:Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.var storeObject = { firstname : '', lastname : ''}Example: http://jsfiddle.net/Gajotres/9KKbx/Solution 3:You can also access data from the previous page like this:$(document).on('pagebeforeshow', '#index',function (e, data) { alert(data.prevPage.attr('id'));});prevPage object holds a complete previous page.Solution 4:As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.if(typeof(Storage)!=="undefined") { localStorage.firstname="Dragan"; localStorage.lastname="Gaic";}Example: http://jsfiddle.net/Gajotres/J9NTr/Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.Don’t Use .live() / .bind() / .delegate()I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.Benchmarking:There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each "change page" is going to show you this data by halting the app) and change it to console.log function.Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....Final notesAlways, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.Changes:30.01.2013 - Added a new method of multiple event triggering prevention31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation18.05.2013 - Added another solution against multiple event binding 这篇关于jQuery Mobile:文档准备与页面事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-24 17:27