jQuery Mobile中的頁面加載與跳轉機制


第一次做用jQuery Mobile做東西,發現一些跟平時的思維習慣不太一樣的。其中這個框架的頁面加載機制便是其中一個。如果不明白其中的奧秘,往往會出現一些讓人摸不着頭腦的怪現象,比如頁面進入后點擊按鈕后Javascript就是不執行,而用F5刷新頁面后又可以正常執行等。

即使我們明白了HTML文件與jQuery Mobile中page概念的區別,也還是不能解決上述問題。當然,了解這個是一個大前提。原來,jQuery Mobile是用Ajax的方式加載所有HTML中的標記data-role="page"的DIV元素中,第一個HTML頁面一般都是完全加載,包括 HEAD BODY 都會被加載到DOM中,完成后便是鏈接到的其他頁面內容的加載。 第二個HTML頁面只有 BODY 中的內容會被以Ajax的方式加載到頭一個HTML的 DOM中。 並且第二HTML頁面的 BODY 中的內容也並非全部加載,而僅僅是其中的第一個帶data-role="page"屬性的DIV會被加載進去,其余的東西則無緣進入頁面渲染。

直接上代碼,或許更容易讓人明白些:

index.html

<!DOCTYPE html>
    <html lang="en">
        <head>
            <!-- META TAGS Declaration -->
            <meta charset="UTF-8">
            <title>TEst</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;" />
            <meta name="apple-mobile-web-app-capable" content="yes" />
            <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
            <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>              
            <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>  
            <script>
            $(document).on('pagebeforeshow', '#foo', function(){ 
                alert($('#body-test').html());
            });
            </script>           
        </head>

        <body id="body-test">
            <div data-role="page" id="portfolio"  data-add-back-btn="true">             
                <div data-role="content" data-theme='c' >
                    <a href="test.html" data-role="button">Go to Bar</a>
                </div>
            </div><!-- Page Project #1 -->
        </body>     
</html>

test.html

<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1"> 
        <link rel="stylesheet" href="style/jquery.mobile-1.3.1.css" />
        <script src="jquery-js/jquery-1.10.1.js"></script>
        <script src="jquery-js/jquery.mobile-1.3.1.js"></script>
        <title>Foobar</title>
    </head>

    <body>
        <div data-role="page" id="foo">
            <div data-role="content">
                <a href="#bar" data-role="button">Go to Bar</a>
            </div>
        </div>

        <div data-role="page" id="bar">
            <div data-role="content">
                <p>Bar</p>
            </div>
        </div>
    </body>
</html>

參考資料來源:http://stackoverflow.com/questions/17403825/link-fails-to-work-unless-refreshing/17403907#17403907


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM