在 jQuery Mobile 中执行 $(document).ready 的正确方法是什么?
假设我想在 jQuery Mobile 完成 UI 渲染后运行一些代码。 mobileinit
事件不起作用,因为它是在发生这种情况之前引发的。快速的 Google 搜索似乎表明,仅使用 $(document).ready
不适用于 JQM;但我只是尝试了它(在 mobileinit
之后调用)并且它对我有用:我的代码运行并动态更新元素等,一切都很好。所以我想知道,是否有某种原因我不应该使用它(它不可靠或搞乱了 JQM),或者是关于它不起作用的信息根本不准确?我缺少什么?
更新:请参阅此处进行演示。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您读到 $(document).ready 不适用于 jQuery Mobile 的原因很可能是它不会在您每次查看伪页面时触发。也就是说,当加载 html 文档时它仍然会触发。
如果您想运行每次查看伪页面时触发的代码,可以使用以下代码:
注意:您还可以绑定其他挂钩(pageshow、pagehide、pagebefoershow、pagebeforehide),可以在此处找到文档:<一href="http://jquerymobile.com/demos/1.0b1/docs/api/events.html">http://jquerymobile.com/demos/1.0b1/docs/api/events.html
< strong>---------- 编辑 ----------
我正在考虑这个,$(document).ready() 的最佳模拟不绑定到“pageshow”事件,它将绑定到“pagecreate”事件。 $(document).ready() 每次页面加载时触发一次,“pagecreate”对伪页面执行相同的操作,而“pageshow”在每次显示页面时触发。
因此,如果用户单击离开主屏幕,然后单击后退按钮返回主屏幕,则“pageshow”将在主屏幕的第二次(以及后续)“显示”时触发。
此外,“pageshow”要求用户导航到它所绑定的页面。
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:
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.