在 jQuery Mobile 中执行 $(document).ready 的正确方法是什么? [英] What's the right way to do $(document).ready in jQuery Mobile?
问题描述
假设我想在 jQuery Mobile 完成 UI 呈现后运行一些代码.mobileinit
事件不起作用,因为它在发生这种情况之前 引发.一个快速的谷歌搜索似乎表明,简单地使用 $(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?
更新:请参阅此处进行演示.
推荐答案
您读到 $(document).ready 不能与 jQuery Mobile 一起使用的最可能原因是它不会在您每次查看伪文件时触发页.也就是说,它仍然会在加载 html 文档时按原样触发.
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
});
注意:您还可以绑定其他钩子(pageshow、pagehide、pagebefoershow、pagebeforehide),文档可以在这里找到:http://jquerymobile.com/demos/1.0b1/docs/api/events.html
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
---------- 编辑 ----------
我正在考虑这个问题,最好的模拟 $(document).ready() 不是绑定到pageshow"事件,而是绑定到pagecreate"事件.$(document).ready() 在每次页面加载时触发一次,pagecreate"对伪页面执行相同的操作,而pageshow"在每次显示页面时触发.
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.
因此,如果用户单击离开主屏幕,然后单击后退按钮返回主屏幕,pageshow"将在主屏幕的第二次(以及后续)显示"时触发.
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.
此外,pageshow"要求用户导航到它所绑定的页面.
Also, "pageshow" requires the user to navigate to the page to which it is bound.
这篇关于在 jQuery Mobile 中执行 $(document).ready 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!