ハマリどころ
jquery mobileを使う上ではまったところのまとめ。
※ある程度jquery mobileを知っている人向けです。
ページ遷移の仕組み(ajaxロード)
デフォルトではページ遷移にajaxが使われます(正確にはajaxを使ってページロードか)。
簡単なサンプル。
■ページ1(page1.html)
<!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" /> <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>header</h1> </div> <div data-role="content"> <p>ページ1</p> <a href="page2.html" data-role="button">ページ2へ</a> </div> <div data-role="footer"> <h4>footer</h4> </div> </div> </body> </html>
■ページ2(page2.html)
<!DOCTYPE html> <html> <head> <title>Page2</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" /> <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>header</h1> </div> <div data-role="content"> <p>ページ2</p> <a href="page1.html" data-role="button">ページ1へ</a> </div> <div data-role="footer"> <h4>footer</h4> </div> </div> </body> </html>
ボタンをクリックすれば、ページ遷移します。
ここで、ポイントが、ページ2に遷移した時点のHTMLがどうなっているか。こんな風になっています(jquery mobileが付与するclassなどがありますので、厳密には実際のものと異なります)。
<!DOCTYPE html> <html> <head> <title>Page Title</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.css" /> <script src="http://code.jquery.com/jquery-1.4.3.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>header</h1> </div> <div data-role="content"> <p>ページ1</p> <a href="page2.html" data-role="button">ページ2へ</a> </div> <div data-role="footer"> <h4>footer</h4> </div> </div> <div data-role="page"> <div data-role="header"> <h1>header</h1> </div> <div data-role="content"> <p>ページ2</p> <a href="page1.html" data-role="button">ページ1へ</a> </div> <div data-role="footer"> <h4>footer</h4> </div> </div> </body> </html>
この時のURLは以下のようになります。
page1.htmlの内容にpage2.htmlのpage部分が追加されるんですねぇ。
よく見ると、ブラウザのページタイトルはPage1のままだったりします。
よって、page2.htmlは実はこれでも普通に動きます。
<div data-role="page"> <div data-role="header"> <h1>header</h1> </div> <div data-role="content"> <p>ページ2</p> <a href="page1.html" data-role="button">ページ1へ</a> </div> <div data-role="footer"> <h4>footer</h4> </div> </div>
ここでのはまりポイントとしては・・
遷移先ページではpage-divに書いていないものは無視される!
htmlファイルごとにidをユニークにするのではなく、ajaxロードされるページ全体でidはユニークでないといけない!
遷移先ページでのみ使用するjavascriptなどをheadタグで宣言しても全く読み込まれません。これではまりました・・・
じゃぁどうするか?
page-div内にjavascriptを書くようにするか、ajaxでの遷移をやめるか、ですね。
ページ2への遷移部分に「rel="external"」と書けば、通常の画面遷移となります。
<a href="page1.html" data-role="button" rel="external">ページ1へ</a>