如何正确使用pageinit? [英] How to use pageinit correctly?

查看:175
本文介绍了如何正确使用pageinit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每个页面都有一个文件,并且我试图在每个页面上实现pageinit事件处理程序(我认为严格属于一个页面的内容应该在此处声明),如下所示:

I have a single file for each page and i am trying to implement the pageinit event handler on every page (I think what belongs strictly to one page, should be declared there) as shown below:

<body>
    <div id="myPage" data-role="page">
        <!-- Content here -->
        <script type="text/javascript">
            $("#myPage").live('pageinit', function() {
                // do something here...
            });
        </script>
    </div>
</body>

该事件已正确绑定到页面,因此将执行代码,但是-现在是我的问题-如果我转到另一个页面并稍后在pageinit事件上返回,则将执行两次.我认为这是因为.live方法将pageinit事件再次绑定到页面.但是pageinit事件不应该在页面初始化时仅调用一次吗?我在这里想念什么?

The event is bound properly to the page, so the code is executed but - now my problem - if i go to another page and return later on the pageinit event will be executed twice. I think that is because the .live method binds the pageinit event again to the page. But shouldn't the pageinit event only called once at page initialization? What I am missing here?

推荐答案

我认为最好将JavaScript代码移动到另一个文件中,因为在您的网站jQuery Mobile上浏览时可能会清理(阅读:从DOM中删除),该myPage页面,因此必须重新加载它,然后重新运行您定义的同一代码块,并为pageinit事件绑定2个侦听器.

I think its probably best to move your JavaScript code into another file as while your navigating around your site jQuery Mobile may cleanup (read: delete from DOM) that myPage page and therefore will have to load it in again and hense rerun that same block of code you defined and bind 2 listeners for the pageinit event.

这基本上就是为什么他们建议使用liveon函数的原因,但是如果您在页面上包含绑定代码,它就会掉下来;)

Thats basically why they suggest using the live or on functions however it falls over if you include the binding code on the page ;)

但是,如果您坚持要在每页上放置代码,则可以使用bind而不是live.

However if you insist on having your code placed on a per page basis than use bind instead of live.

参考: http://jquerymobile.com/demos/1.0/docs/pages/page-cache.html

因此,jQuery Mobile具有一种简单的机制来保持DOM整洁.每当它通过Ajax加载页面时,当您稍后离开页面时(技术上是在pagehide事件上),jQuery Mobile都会将该页面标记为从DOM中删除.

jQuery Mobile therefore has a simple mechanism to keep the DOM tidy. Whenever it loads a page via Ajax, jQuery Mobile flags the page to be removed from the DOM when you navigate away from it later (technically, on the pagehide event).

这篇关于如何正确使用pageinit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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