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

时间秒杀一切 提交于 2019-11-30 03:45:47

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!