What's the right way to do $(document).ready in jQuery Mobile?

后端 未结 1 1917
旧巷少年郎
旧巷少年郎 2020-12-28 17:02

Suppose I want to run some code once jQuery Mobile has finished rendering the UI. The mobileinit event doesn\'t work since it\'s raised before this hap

1条回答
  •  被撕碎了的回忆
    2020-12-28 17:20

    Most likely the reason you read that $(document).ready won't work with jQuery Mobile is that it does not fire each time you view a pseudo-page. That said, it still triggers as it should when the html document is loaded.

    If you want to run code that triggers each time you view a pseudo-page you can use this code:

    $('[data-role="page"]').live('pageshow', function () {
        //run your code here
    });
    

    NOTE: there are other hooks that you can bind to as well (pageshow, pagehide, pagebefoershow, pagebeforehide), documentation can be found here: http://jquerymobile.com/demos/1.0b1/docs/api/events.html

    ---------- EDIT ----------

    I was thinking about this and the best analog to $(document).ready() is not binding to the "pageshow" event, it would be binding to the "pagecreate" event. $(document).ready() fires once per page load, and "pagecreate" does the same for pseudo-pages whereas "pageshow" fires each time a page is displayed.

    So if a user clicked away from the home-screen and then clicked a back button to return to the home-screen, "pageshow" would fire on this second (and subsequent) "showing" of the home-screen.

    Also, "pageshow" requires the user to navigate to the page to which it is bound.

    0 讨论(0)
提交回复
热议问题