简体   繁体   English

jQuery Mobile:准备文档与页面事件

[英]jQuery Mobile: document ready vs. page events

I am using jQuery Mobile, and I am having trouble understanding differences between classic document ready and jQuery Mobile page events. 我正在使用jQuery Mobile,并且无法理解经典文档就绪和jQuery Mobile页面事件之间的区别。

  1. What is the real difference? 真正的区别是什么?

    Why should 为什么要

     <!-- language: lang-js --> $(document).ready() { }); 

    be better than 胜过

     $(document).on('pageinit') { }); 
  2. What is the order of page events, when you transition from one page to another? 从一页切换到另一页时,页面事件的顺序是什么?

  3. 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: jQuery Mobile 1.4更新:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. 我的原始文章旨在用于页面处理的旧方法,基本上是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. 现在不赞成使用旧的处理方式,它会一直保持有效状态,直到(包括)jQuery Mobile 1.5,因此您仍然可以使用下面提到的所有功能,至少直到明年和jQuery Mobile 1.6为止。

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. 包括pageinit在内的旧事件不存在,它们已替换为pagecontainer小部件。 Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed. Pageinit被完全擦除,您可以使用pagecreate来代替,该事件保持不变,并且不会被更改。

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. 即使您正在使用jQuery Mobile 1.4或更高版本,也应该阅读此答案,它不仅仅包含页面事件,因此您可能会发现很多有用的信息。

Older content: 较旧的内容:

This article can also be found as a part of my blog HERE . 本文也可以在我的博客HERE中找到

$(document).on('pageinit') vs $(document).ready() $(document).on('pageinit')$(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. jQuery中学习的第一件事是调用$(document).ready()函数中的代码,以便一旦加载DOM,一切都将执行。 However, in jQuery Mobile , Ajax is used to load the contents of each page into the DOM as you navigate. 但是,在jQuery Mobile中 ,Ajax用于在导航时将每个页面的内容加载到DOM中。 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. 因此, $(document).ready()将在加载第一页之前触发,并且用于页面操作的每个代码都将在刷新页面后执行。 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: 经典jQuery语法:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. 为了解决此问题(并相信我这是一个问题), jQuery Mobile开发人员创建了页面事件。 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: 这些页面事件之一是pageinit事件,我们可以像这样使用它:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. 我们甚至可以走得更远,使用页面ID代替文档选择器。 Let's say we have jQuery Mobile page with an id index : 假设我们有一个带有id 索引的 jQuery Mobile页面:

<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. Pageinit事件将在每次将要第一次加载并显示页面时执行。 It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. 除非手动刷新页面或关闭Ajax页面加载,否则不会再次触发。 In case you want code to execute every time you visit a page it is better to use pagebeforeshow event. 如果您希望每次访问页面都执行代码,最好使用pagebeforeshow事件。

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem. 这是一个工作示例: http : //jsfiddle.net/Gajotres/Q3Usv/来演示此问题。

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. 无论您使用的是1个html多个页面还是多个HTML文件范例,建议您将所有自定义JavaScript页面处理都分成一个单独的JavaScript文件。 This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application. 这将使您的代码变得更好,但是您将获得更好的代码概述,尤其是在创建jQuery Mobile应用程序时。

There's also another special jQuery Mobile event and it is called mobileinit . 还有另一个特殊的jQuery Mobile事件,称为mobileinit When jQuery Mobile starts, it triggers a mobileinit event on the document object. jQuery Mobile启动时,它将触发文档对象上的mobileinit事件。 To override default settings, bind them to mobileinit . 要覆盖默认设置,请将它们绑定到mobileinit One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior. 使用mobileinit的一个很好的例子是关闭Ajax页面加载,或更改默认的Ajax加载器行为。

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order 页面事件转换顺序

First all events can be found here: http://api.jquerymobile.com/category/events/ 首先,所有事件都可以在这里找到: http : //api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order: 假设我们有一个页面A和一个页面B,这是一个卸载/加载顺序:

  1. page B - event pagebeforecreate 页面B-事件pagebeforecreate

  2. page B - event pagecreate 页面B-事件页面创建

  3. page B - event pageinit 页面B-事件pageinit

  4. page A - event pagebeforehide A页-事件pagebehidehide

  5. page A - event pageremove 页面A-事件页面删除

  6. page A - event pagehide A页-事件pagehide

  7. page B - event pagebeforeshow 页面B-事件页面

  8. page B - event pageshow 页面B-活动页面显示

For better page events understanding read this: 为了更好地了解页面事件,请阅读以下内容:

  • pagebeforeload , pageload and pageloadfailed are fired when an external page is loaded pagebeforeloadpageloadpageloadfailed当外部加载页面时被解雇
  • pagebeforechange , pagechange and pagechangefailed are page change events. pagebeforechangepagechangepagechangefailed是页面更改事件。 These events are fired when a user is navigating between pages in the applications. 当用户在应用程序中的页面之间导航时,将触发这些事件。
  • pagebeforeshow , pagebeforehide , pageshow and pagehide are page transition events. pagebeforeshowpagebeforehidepageshowpagehide是页面转换事件。 These events are fired before, during and after a transition and are named. 这些事件在转换之前,期间和之后都会触发,并被命名。
  • pagebeforecreate , pagecreate and pageinit are for page initialization. pagebeforecreatepagecreatepageinit用于页面初始化。
  • pageremove can be fired and then handled when a page is removed from the DOM 当从DOM中删除页面时,可以触发pageremove并进行处理

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/ 页面加载jsFiddle示例: http//jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire. 如果未启用AJAX,则某些事件可能不会触发。

Prevent page transition 防止页面过渡

If 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/triggering 防止多个事件绑定/触发

jQuery Mobile works in a different way than classic web applications. jQuery Mobile工作方式不同于经典Web应用程序。 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. 这不是错误,只是jQuery Mobile处理其页面的方式。 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/ 可用的jsFiddle示例: http//jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button . 每次您访问页面#index click事件都将绑定到#test-button按钮 Test it by moving from page 1 to page 2 and back several times. 从第1页移至第2页并多次返回进行测试。 There are few ways to prevent this problem: 有几种方法可以防止此问题:

Solution 1 解决方案1

Best solution would be to use pageinit to bind events. 最好的解决方案是使用pageinit绑定事件。 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. 如果您查看官方文档,就会发现pageinit仅会触发一次,就像准备好文档一样,因此不可能再次绑定事件。 This is best solution because you don't have processing overhead like when removing events with off method. 这是最好的解决方案,因为您没有像使用off方法删除事件时那样的处理开销。

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/ 可用的jsFiddle示例: http//jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example. 该工作解决方案是在先前有问题的示例的基础上提出的。

Solution 2 解决方案2

Remove 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/ 可行的jsFiddle示例: http//jsfiddle.net/Gajotres/K8YmG/

Solution 3 解决方案3

Use a jQuery Filter selector, like this: 使用jQuery筛选器选择器,如下所示:

$('#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/ 由于事件过滤器不是官方jQuery框架的一部分,因此可以在以下位置找到: 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. 简而言之,如果您最关心速度,那么解决方案2比解决方案1更好。

Solution 4 解决方案4

A 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/ 可用的jsFiddle示例: 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/ 对于此解决方案,请向sholsinger发送Tnxhttp : //sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice pageChange事件怪癖-触发两次

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before. 有时pagechange事件可以触发两次,并且与前面提到的问题无关。

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. pagebeforechange事件发生两次的原因是由于toPage不是jQuery增强的DOM对象时changePage中的递归调用。 This recursion is dangerous, as the developer is allowed to change the toPage within the event. 这种递归很危险,因为允许开发人员在事件内更改toPage。 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. 如果开发人员在pagebeforechange事件处理程序中始终将toPage设置为字符串,则无论它是否是对象,都将导致无限递归循环。 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). pageload事件将新页面作为数据对象的page属性传递(应将其添加到文档中,当前未列出)。 The pageload event could therefore be used to access the loaded page. 因此,pageload事件可用于访问已加载的页面。

In few words this is happening because you are sending additional parameters through pageChange. 简而言之,这是因为您正在通过pageChange发送其他参数。

Example: 例:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order . 要解决此问题,请使用“页面事件转换顺序”中列出的任何页面事件。

Page Change Times 页面更改时间

As 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. 如前所述,当您从一个jQuery Mobile页面更改为另一页面时,通常是通过单击DOM中已经存在的另一个jQuery Mobile页面的链接,或者通过手动调用$ .mobile.changePage来进行,会发生多个事件和后续操作。 At a high level the following actions occur: 在较高级别上,将发生以下操作:

  • A page change process is begun 页面更改过程已开始
  • A new page is loaded 载入新页面
  • The content for that page is “enhanced” (styled) 该页面的内容已“增强”(样式化)
  • A transition (slide/pop/etc) from the existing page to the new page occurs 从现有页面到新页面的过渡(幻灯片/弹出/等)

This is a average page transition benchmark: 这是一个平均页面过渡基准:

Page load and processing: 3 ms 页面加载和处理: 3毫秒

Page enhance: 45 ms 页面增强: 45毫秒

Transition: 604 ms 转换时间: 604毫秒

Total time: 670 ms 总时间: 670毫秒

*These values are in milliseconds. *这些值以毫秒为单位。

So as you can see a transition event is eating almost 90% of execution time. 因此,您可以看到过渡事件几乎消耗了90%的执行时间。

Data/Parameters manipulation between page transitions 页面转换之间的数据/参数操作

It 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/1848600 参考: https : //stackoverflow.com/a/13932240/1848600

Solution 1: 解决方案1:

You can pass values with changePage: 您可以使用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 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 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: 解决方案2:

Or you can create a persistent JavaScript object for a storage purpose. 或者,您可以创建一个持久性JavaScript对象以用于存储。 As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active. 只要将Ajax用于页面加载(并且不会以任何方式重新加载页面),该对象就会保持活动状态。

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/ 示例: http//jsfiddle.net/Gajotres/9KKbx/

Solution 3: 解决方案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. prevPage对象保存完整的上一页。

Solution 4: 解决方案4:

As a last solution we have a nifty HTML implementation of localStorage. 作为最后的解决方案,我们有一个很棒的localStorage HTML实现。 It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh. 它仅适用于HTML5浏览器(包括Android和iOS浏览器),但所有存储的数据都可以通过页面刷新保持不变。

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/ 示例: http//jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. 可能是最佳解决方案,但在某些版本的iOS 5.X中将失败。 It is a well know error. 这是一个众所周知的错误。

Don't Use .live() / .bind() / .delegate() 不要使用.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. 我忘了提及(和tnx andleer提醒我),不建议使用on / off进行事件绑定/解除绑定,不赞成使用live / die和bind / unbind。

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. jQuery的.live()方法在1.3版引入API时被视为天赐之物。 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. 在典型的jQuery应用程序中,可能会有许多DOM操作,并且随着元素的来去去去钩挂和脱钩会变得非常繁琐。 The .live() method made it possible to hook an event for the life of the app based on its selector. .live()方法可以根据应用程序的选择器在应用程序的生命期内挂钩事件。 Great right? 很好吗? Wrong, the .live() method is extremely slow. 错误的.live()方法非常慢。 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. .live()方法实际上将其事件挂接到文档对象,这意味着该事件必须从生成该事件的元素起泡直到到达文档。 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. jQuery团队的人们不再推荐使用它,我也不推荐使用。即使挂接和取消挂接事件可能很繁琐,但是如果没有.live()方法,您的代码将比使用它快得多。

Instead of .live() you should use .on() . 代替.live()您应该使用.on() .on() is about 2-3x faster than .live() . .on().live()快大约2-3倍。 Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34 , everything will be clear from there. 看一下该事件绑定基准: http : //jsperf.com/jquery-live-vs-delegate-vs-on/34 ,从那里可以清楚地看到所有内容。

Benchmarking: 基准测试:

There's an excellent script made for jQuery Mobile page events benchmarking. jQuery Mobile页面事件基准测试有一个出色的脚本。 It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js . 可以在这里找到: 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. 但是在您执行任何操作之前,我建议您删除其alert通知系统(每个“更改页”将通过停止应用程序向您显示此数据),并将其更改为console.log函数。

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 .... 基本上,此脚本将记录您的所有页面事件,如果您仔细阅读本文(页面事件描述),您将知道jQm在页面增强,页面转换...上花费了多少时间。

Final notes 最后的笔记

Always, and I mean always read official jQuery Mobile documentation. 始终如此,我的意思是始终阅读jQuery Mobile官方文档。 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 prevention 30.01.2013-添加了防止多事件触发的新方法
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions 2013年1月31日-为页面转换之间的数据/参数操作一章添加了更好的说明
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions 2013年3月2日- 在页面转换之间的数据/参数操作一章中添加了新的内容/示例
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation 2013年5月22日-添加了用于防止页面过渡/更改的解决方案,并添加了指向官方页面事件API文档的链接
  • 18.05.2013 - Added another solution against multiple event binding 2013年5月18日-添加了另一个针对多个事件绑定的解决方案

Some of you might find this useful. 你们中的有些人可能会发现这很有用。 Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console ( Ctrl + Shift + I ). 只需将其复制粘贴到您的页面上,您将获得在Chrome控制台中触发事件的顺序( Ctrl + Shift + I )。

$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});

You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). 您不会在控制台中看到卸载,因为在卸载页面时(当您离开页面时)会被触发。 Use it like this: 像这样使用它:

$(window).unload(function () { debugger; console.log("window unloaded");});

And you will see what I mean. 您会明白我的意思。

This is the correct way: 这是正确的方法:

To execute code that will only be available to the index page, we could use this syntax: 要执行仅对索引页可用的代码,我们可以使用以下语法:

$(document).on('pageinit', "#index",  function() {
    ...
});

The simple difference between document ready and page event in jQuery-mobile is that: jQuery-mobile中的文档就绪和页面事件之间的简单区别是:

  1. The document ready event is used for the whole HTML page, 文档就绪事件用于整个HTML页面,

     $(document).ready(function(e) { // Your code }); 
  2. When there is a page event, use for handling particular page event: 当有页面事件时,用于处理特定的页面事件:

     <div data-role="page" id="second"> <div data-role="header"> <h3> Page header </h3> </div> <div data-role="content"> Page content </div> <!--content--> <div data-role="footer"> Page footer </div> <!--footer--> </div><!--page--> 

You can also use document for handling the pageinit event: 您还可以使用文档来处理pageinit事件:

$(document).on('pageinit', "#mypage", function() {

});

While you use .on(), it's basically a live query that you are using. 使用.on()时,它基本上是您正在使用的实时查询。

On the other hand, .ready (as in your case) is a static query. 另一方面,.ready(根据您的情况)是静态查询。 While using it, you can dynamically update data and do not have to wait for the page to load. 使用它时,您可以动态更新数据,而不必等待页面加载。 You can simply pass on the values into your database (if required) when a particular value is entered. 输入特定值后,您可以简单地将值传递到数据库中(如果需要)。

The use of live queries is common in forms where we enter data (account or posts or even comments). 在我们输入数据(帐户或帖子甚至评论)的表单中,经常使用实时查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM