问题
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