jQuery Mobile - pageinit handler not called on subsequent changePage calls

好久不见. 提交于 2019-12-24 12:40:25

问题


I have two jquery mobile "pages" (divs designated as pages) on the html page. I want to call methods every time I go to a page. I hook up methods to fire on 'pageinit' event. However, it only gets called once and doesn't get called on subsequent changePage calls.

Here is a jsFiddle to demonstrate. ( time stamp should change on pageinit )

Here is my code in entirety https://gist.github.com/dev-e-loper/5356942

My pages:

<div id="page1" data-role="page">
     <h1>One</h1>
 <a id="page1_link" data-role="button">go to page 2</a>

    <div id="page1_output"></div>
</div>
<div id="page2" data-role="page">
     <h1>Two</h1>
 <a id="page2_link" data-role="button">go to page 1</a>

    <div id="page2_output"></div>
</div>

Code to hook up pageinit handlers:

$("#page1").live('pageinit', function () {
    $("#page1_output").append('<br/> page 1 initialized. time - ' + new Date());
});


$("#page2").live('pageinit', function () {
    $("#page2_output").append('<br/> page 2 initialized time - ' + new Date());
});


$("#page1_link").live('click', function () {

    $.mobile.changePage($("#page2"));

});

$("#page2_link").live('click', function () {

    $.mobile.changePage($("#page1"));

});

回答1:


pageinit will fire when your page first loads. Both of your pages are cached within the DOM so that event will only fire once. Try pageshow which will fire each time the page is shown.

Also, live() is depreciated. You should use bind() or on().

http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html

$("#page1").bind('pageshow', function () {
    $("#page1_output").append('<br/> page 1 initialized. time - ' + new Date());
});


$("#page2").bind('pageshow', function () {
    $("#page2_output").append('<br/> page 2 initialized time - ' + new Date());
});


来源:https://stackoverflow.com/questions/15933134/jquery-mobile-pageinit-handler-not-called-on-subsequent-changepage-calls

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