在jQuery Mobile中执行$(document).ready的正确方法是什么? [英] What's the right way to do $(document).ready in jQuery Mobile?

查看:101
本文介绍了在jQuery Mobile中执行$(document).ready的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设jQuery Mobile完成呈现UI后,我想运行一些代码. mobileinit事件不起作用,因为它是在之前引发的.快速的Google搜索似乎表明,仅使用$(document).ready不能与JQM一起使用.但是我只是尝试了一下(在mobileinit之后调用),它对我有用:我的代码运行并动态更新了元素,等等,一切都很好.所以我想知道,是出于某些原因,我不应该使用它(它不可靠或弄乱了JQM),还是有关它的信息不能简单地不准确地工作?我想念什么?

更新:有关演示,请参见此处.

解决方案

您读到$(document).ready不适用于jQuery Mobile的原因很可能是,每次查看伪代码时,它都不会触发页.就是说,它仍然会在加载html文档时触发.

如果您想运行每次查看伪页面时都会触发的代码,则可以使用以下代码:

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

注意:还可以绑定其他钩子(pageshow,pagehide,pagebefoershow,pagebeforehide),可以在这里找到文档:

因此,如果用户单击离开主屏幕的位置,然后单击后退按钮以返回主屏幕,则页面显示"将在主屏幕的第二(和后续)显示"中触发. /p>

此外,页面显示"还要求用户导航到该页面所绑定的页面.

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 happens. A quick Google search seems to indicate that simply using $(document).ready won't work with JQM; but I just tried it (called after mobileinit) and it worked for me: my code ran and dynamically updated elements, etc. just fine. So I'm wondering, is there some reason I shouldn't be using it (it's unreliable or messes up JQM), or is the information out there about it not working simply inaccurate? What am I missing?

Update: See here for a demonstration.

解决方案

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.

这篇关于在jQuery Mobile中执行$(document).ready的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆