JQuery mobile, multi-page event

I have two pages: test1.html and test2.html. Every time one of these pages becomes visible, I want to execute some code.

Here are two pages:

test1.html:

<!DOCTYPE html> <html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test1</title> <link rel="stylesheet" href="css/jquery.mobile-1.2.0.css" /> <script src="js/jquery.js"></script> <script src="js/jquery.mobile-1.2.0.js"></script> </head><body> <div data-role="page" id="test1"> <div data-role="content"> <a href="test2.html" data-role="button">jump to test2</a> </div> </div> <script type="text/javascript"> $(document).on('pageshow', '#test1', function (data) { alert('pageshow test1'); }); </script> </body></html> 

test2.html:

 <!DOCTYPE html> <html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>test1</title> <link rel="stylesheet" href="css/jquery.mobile-1.2.0.css" /> <script src="js/jquery.js"></script> <script src="js/jquery.mobile-1.2.0.js"></script> </head><body> <div data-role="page" id="test2"> <div data-role="content"> <a href="test1.html" data-role="button">jump to test1</a> </div> </div> <script type="text/javascript"> $(document).on('pageshow', '#test2', function (data) { alert('pageshow test2'); }); </script> </body></html> 

When I start with test1.html, I get a warning only for test1 (also every time I return to it), but never for test2.html.

I need a show handler that is different for each page.

+4
source share
1 answer

Available Solutions

Solution 1

First remove the javascript code from the BODY page and put it in a single js file. This new js file should be placed in HEAD after the initialization of js / jquery.mobile-1.2.0.js.

Something like that:

 <script src="js/jquery.js"></script> <script src="js/jquery.mobile-1.2.0.js"></script> <script src="js/custom.js"></script> 

In your case, jQuery mobile loads the second HTML file, but only this part:

 <div data-role="page" id="test2"> <div data-role="content"> <a href="test1.html" data-role="button">jump to test1</a> </div> </div> 

It will be loaded using ajax into the DOM structure. This is the main reason why the second page of the script is not executed.

Decision 2

The second solution is to use the rel="external" attribute in your links, this will force a page reload each time a new page is opened.

 <a href="test1.html" data-role="button" rel="external">jump to test1</a> 

Regardless of the fact that, if possible, never use the SCRIPT tag inside the BODY page, it will work, but at the same time it can cause additional problems.

Additional Information

If you want to know more about this problem, then how to solve it + examples take a look at this article strong> I did on my personal blog . This article deals directly with this topic, so I hope you do not see it as an attempt at self-promotion.

+2
source

All Articles