开发者

How to trigger an event on show and hide of one page only in jQuery Mobile app

Ok, so I am beginning working with jQuery Mobile. I am far from being a javascript expert. jQuery Mobile is very cool, but it has me stumped on this one issue.

I have a need to run some code when a certain page is shown, and then another when it is hidden - but only a certain page of the hierarchy. I know how to use the pagecreate and pageshow events (and have used开发者_JS百科 these to work with code that needs to run with every page). However I need to be able to detect when a particular page is shown and when it is hidden.

So what have I tried? I put a custom attribute on the following tag on the page:

<div data-role="content" myspecialattribute="true">

Then in the pageshow event, I used jqmData() to search for that element. This was successful, the first time the page is encountered, and then does not work. Due to the way that JQM loads the pages, that tag and that attribute is then always found in the dom, even if I move to other pages, as JQM is using clever ajax showing/hiding of the page.

I have spent a number of hours looking for a solution - but my javascript skills are just not there. I presume this is easy, so I feel a bit foolish asking for help.


You need to add an id to the page and use live live() to trigger the event needed, Live Example:

  • http://jsfiddle.net/phillpafford/U3VxB/

JS:

$('#page2').live('pageshow',function(event, ui){
    alert('Alert for page 2 only');
});

HTML:

<div data-role="page" id="home"> 
    <div data-role="content"> 

        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f"> 
            <li data-role="list-divider">Navigation</li> 
            <li><a href="#page2">Page 2</a></li> 
        </ul> 

    </div>
</div>

<div data-role="page" id="page2"> 
    <div data-role="content"> 

        <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="f"> 
            <li data-role="list-divider">Navigation</li> 
            <li><a href="#home">Home Page</a></li> 
        </ul> 

    </div>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜