Javascript jQuery Mobile:文档就绪与页面事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14468659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:53:15  来源:igfitidea点击:

jQuery Mobile: document ready vs. page events

javascriptjqueryhtmljquery-mobilecordova

提问by user2001897

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?

  1. 真正的区别是什么?

    为什么要

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

    $(document).on('pageinit') {
    
    });
    
  2. 当您从一个页面转换到另一个页面时,页面事件的顺序是什么?

  3. 如何将数据从一个页面发送到另一个页面,是否可以访问上一页的数据?

回答by Gajotres

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. 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.4 之前的所有内容。旧的处理方式现在已弃用,它会一直保持活动状态直到(包括)jQuery Mobile 1.5,因此您仍然可以使用下面提到的所有内容,至少在明年和 jQuery Mobile 1.6 之前。

Old events, including pageinitdon't exist any more, they are replaced with pagecontainerwidget. Pageinitis erased completely and you can use pagecreateinstead, that event stayed the same and its not going to be changed.

旧事件,包括pageinit不存在了,它们被替换为pagecontainer部件。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.

这篇文章也可以作为我博客的一部分在这里找到

$(document).on('pageinit')vs $(document).ready()

$(document).on('pageinit')对比 $(document).ready()

The first thing you learn in jQueryis 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.

您在jQuery 中学习的第一件事是在$(document).ready()函数内部调用代码,以便在加载 DOM 后立即执行所有内容。但是,在jQuery Mobile 中,Ajax 用于在您导航时将每个页面的内容加载到 DOM 中。因为这$(document).ready()将在您的第一个页面加载之前触发,并且每个用于页面操作的代码都将在页面刷新后执行。这可能是一个非常微妙的错误。在某些系统上,它可能看起来运行良好,但在其他系统上,它可能会导致出现不稳定、难以重复的怪异现象。

Classic jQuery syntax:

经典的 jQuery 语法:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobiledevelopers 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 pageinitevent and we can use it like this:

为了解决这个问题(相信我这是一个问题),jQuery Mobile开发人员创建了页面事件。简而言之,页面事件是在页面执行的特定点触发的事件。其中一个页面事件是pageinit事件,我们可以这样使用它:

$(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:

我们可以更进一步,使用页面 id 代替文档选择器。假设我们有一个带有 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() {

});

Pageinitevent 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 pagebeforeshowevent.

每次页面即将被加载和第一次显示时,都会执行Pageinit事件。除非手动刷新页面或关闭 Ajax 页面加载,否则它不会再次触发。如果您希望每次访问页面时都执行代码,最好使用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. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobileapplication.

关于这个问题的更多说明。无论您是使用 1 html 多页面还是多个 HTML 文件范例,建议将所有自定义 JavaScript 页面处理分离到一个单独的 JavaScript 文件中。这将使您的代码变得更好,但您将获得更好的代码概览,尤其是在创建jQuery Mobile应用程序时。

There's also another special jQuery Mobileevent and it is called mobileinit. When jQuery Mobilestarts, it triggers a mobileinitevent on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinitusage is turning off Ajax page loading, or changing default Ajax loader behavior.

还有另一个特殊的jQuery Mobile事件,它被称为mobileinit。当jQuery Mobile启动时,它会在文档对象上触发mobileinit事件。要覆盖默认设置,请将它们绑定到mobileinitmobileinit使用的一个很好的例子是关闭 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

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

  1. 页面 B - 事件页面beforecreate

  2. 页面 B - 事件页面创建

  3. 页面 B - 事件pageinit

  4. page A - 事件pagebeforehide

  5. page A - 事件pageremove

  6. 页面 A - 事件页面隐藏

  7. 页面 B - 事件页面beforeshow

  8. 页面 B - 活动页面展示

For better page events understanding read this:

为了更好地理解页面事件,请阅读以下内容:

  • pagebeforeload, pageloadand pageloadfailedare fired when an external page is loaded
  • pagebeforechange, pagechangeand pagechangefailedare page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshowand pagehideare page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreateand pageinitare for page initialization.
  • pageremovecan be fired and then handled when a page is removed from the DOM
  • pagebeforeload,pageloadpageloadfailed在加载外部页面时触发
  • pagebeforechangepagechangepagechangefailed在页面更改事件。当用户在应用程序的页面之间导航时会触发这些事件。
  • pagebeforeshowpagebeforehidepageshowpagehide是页面转换事件。这些事件在转换之前、期间和之后被触发并被命名。
  • pagebeforecreatepagecreate并且pageinit是页面初始化。
  • pageremove可以在页面从 DOM 中移除时被触发然后处理

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 Mobileworks 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 Mobilehandles its pages. For example, take a look at this code snippet:

jQuery Mobile以不同于经典 Web 应用程序的方式工作。根据您每次访问某个页面时如何设法绑定事件,它会一遍又一遍地绑定事件。这不是错误,它只是如何jQuery Mobile处理其页面。例如,看看这个代码片段:

$(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 #indexclick 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:

每次访问页面时,#index点击事件都将绑定到按钮#test-button。通过从第 1 页移动到第 2 页并返回几次来测试它。有几种方法可以防止此问题:

Solution 1

解决方案1

Best solution would be to use pageinitto bind events. If you take a look at an official documentation you will find out that pageinitwill 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.

最好的解决方案是使用pageinit绑定事件。如果您查看官方文档,您会发现它pageinit只会触发一次,就像文档就绪一样,因此无法再次绑定事件。这是最好的解决方案,因为您没有像使用 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 2is 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 sholsingerfor this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

将此解决方案的Tnx 发送给sholsingerhttp: //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. 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.

pagebeforechange 事件发生两次的原因是由于当 toPage 不是 jQuery 增强的 DOM 对象时,changePage 中的递归调用。这种递归是危险的,因为开发人员可以在事件中更改 toPage。如果开发人员始终将 toPage 设置为字符串,则在 pagebeforechange 事件处理程序中,无论它是否是对象,都会导致无限递归循环。pageload 事件将新页面作为数据对象的页面属性传递(这应该添加到文档中,当前未列出)。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. At a high level the following actions occur:

如上所述,当您从一个 jQuery Mobile 页面切换到另一个页面时,通常是通过单击指向 DOM 中已存在的另一个 jQuery Mobile 页面的链接,或者通过手动调用 $.mobile.changePage,将发生多个事件和后续操作。在较高级别会发生以下操作:

  • 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

索引.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

第二个.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. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

或者您可以为存储目的创建一个持久性 JavaScript 对象。只要 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'));
});

prevPageobject holds a complete previous page.

prevPage对象保存完整的前一页。

Solution 4:

解决方案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.

作为最后一个解决方案,我们有一个漂亮的 localStorage 的 HTML 实现。它仅适用于 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. It is a well know error.

可能是最好的解决方案,但它会在某些版本的 iOS 5.X 中失败。这是一个众所周知的错误。

Don't Use .live()/ .bind()/ .delegate()

不要使用.live()/ .bind()/.delegate()

I forgot to mention (and tnx andleerfor 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. 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.

jQuery 的 .live() 方法在 1.3 版中引入 API 时被视为天赐之物。在一个典型的 jQuery 应用程序中,可能会有很多 DOM 操作,并且随着元素的来来去去,钩子和解钩会变得非常乏味。该.live()方法可以根据其选择器在应用程序的生命周期内挂钩一个事件。很棒吧?错了,.live()方法极其缓慢。该.live()方法实际上将其事件挂钩到文档对象,这意味着该事件必须从生成事件的元素冒泡,直到它到达文档。这可能非常耗时。

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(). .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.

而不是.live()你应该使用.on(). .on().live()快大约 2-3 倍。看看这个事件绑定基准:http: //jsperf.com/jquery-live-vs-delegate-vs-on/34,一切都会从那里清楚。

Benchmarking:

基准测试:

There's an excellent script made for jQuery Mobilepage 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 alertnotification system (each “change page” is going to show you this data by halting the app) and change it to console.logfunction.

有一个用于jQuery Mobile页面事件基准测试的优秀脚本。可以在这里找到:https: //github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js。但在你对它做任何事情之前,我建议你删除它的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 Mobiledocumentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

总是,我的意思是总是阅读官方的jQuery Mobile文档。它通常会为您提供所需的信息,并且与其他一些文档不同,这个文档相当不错,有足够的解释和代码示例。

Changes:

变化:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding
  • 30.01.2013 - 添加了多事件触发预防的新方法
  • 31.01.2013 - 为页面转换之间的数据/参数操作章节添加了更好的说明
  • 03.02.2013 -在页面转换之间的数据/参数操作一章中添加了新内容/示例
  • 22.05.2013 - 添加了页面转换/更改预防的解决方案,并添加了指向官方页面事件 API 文档的链接
  • 18.05.2013 - 添加了另一个针对多事件绑定的解决方案

回答by Matas Vaitkevicius

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.

你会明白我的意思。

回答by kecco

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() {
    ...
});

回答by LeoMobDev

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,

    $(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-->
    
  1. 文档就绪事件用于整个 HTML 页面,

    $(document).ready(function(e) {
        // Your code
    });
    
  2. 当有页面事件时,用于处理特定的页面事件:

    <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:

您还可以使用 document 来处理 pageinit 事件:

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

});

回答by Pranjal

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. 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.

另一方面, .ready (如您的情况)是静态查询。使用时可以动态更新数据,无需等待页面加载。当输入特定值时,您可以简单地将值传递到您的数据库(如果需要)。

The use of live queries is common in forms where we enter data (account or posts or even comments).

实时查询的使用在我们输入数据(帐户或帖子甚至评论)的表单中很常见。