单击后通过 JavaScript 动态创建 jQuery Mobile 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6050384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:02:23  来源:igfitidea点击:

Dynamically create jQuery Mobile page via JavaScript after clicking

javascriptjquerynavigationjquery-mobile

提问by Witek

My jQuery Mobile app consists of a single index.htmlpage and contains only one page with a link on startup:

我的 jQuery Mobile 应用程序由一个index.html页面组成,并且在启动时只包含一个带有链接的页面:

<div data-role="page">
  <div data-role="content">
    <a id="startPageLink" href="startPage">start</a>
  </div>
</div>

When the user clicks on the start link, I want to load the content for the startPagefrom my JSON api asynchronously. On the callback I would like to create all the required DOM elements for startPagevia JavaScript and add the content to it. I have created a createStartPage(data)method for this.

当用户单击开始链接时,我想startPage从我的 JSON api 异步加载内容。在回调中,我想startPage通过 JavaScript创建所有必需的 DOM 元素并将内容添加到其中。我createStartPage(data)为此创建了一个方法。

What is the right way to implement such dynamically created pages, so that opening index.html#startPagealso works? I think there should be a way to hook into $.mobile.changePage()to include custom loading/page-creation code, but I did not find anything. Or is there a better solution for this problem?

实现这种动态创建的页面的正确方法是什么,以便打开index.html#startPage也可以工作?我认为应该有一种方法可以$.mobile.changePage()包含自定义加载/页面创建代码,但我没有找到任何东西。或者对于这个问题有更好的解决方案吗?

回答by Jasper

I had some time to mess around with this and I've found a solution that works (tested).

我有一些时间来解决这个问题,我找到了一个有效的解决方案(经过测试)。

SOME NOTES:

一些注意事项:

  1. the javascript encapsulated in $(document).ready(); is for dynamically creating a page if the user navigates to your index.html file with a hash mark already appended (i.e. index.html#some_hash_mark).
  2. The function, create_page(page_id) is for creating a page from a link (or programatically if you like).
  3. Note that the jquery core script and the jquery mobile css are loaded before the $(document).ready() statement but that the jquery mobile script is loaded after.
  4. See that the body tag has been given an id that is refrenced when appending pages to it.
  1. $(document).ready()中封装的javascript;用于动态创建页面,如果用户导航到您的 index.html 文件已经附加了哈希标记(即 index.html#some_hash_mark)。
  2. 函数 create_page(page_id) 用于从链接创建页面(或者如果您愿意,可以通过编程方式)。
  3. 请注意,jquery 核心脚本和 jquery mobile css 在 $(document).ready() 语句之前加载,但 jquery mobile 脚本在之后加载。
  4. 看到 body 标签被赋予了一个 id,在向它添加页面时会被引用。

Document Sample

文件样本

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css"/>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
$(document).ready(function() {

    //check if hash exists and that it is not for the home screen
    if (window.location.hash != '' && window.location.hash != '#page_0') {

        //set whatever content you want to put into the new page
        var content_string = 'Some ' + window.location.hash + ' text...<br><br><a href="#page_0">go to home screen</a>';

        //append the new page onto the end of the body
        $('#page_body').append('<div data-role="page" id="' + window.location.hash.replace('#','') + '"><div data-role="content">' + content_string + '</div></div>');

        //add a link on the home screen to navaigate to the new page (just so nav isn't broken if user goes from new page to home screen)
        $('#page_0 div[data-role="content"]').append('<br><br><a href="#' + window.location.hash.replace('#','') + '">go to ' + window.location.hash.replace('#','') + ' page</a>');
    }
});
function create_page(page_id) {

    //set whatever content you want to put into the new page
    var string = 'FOO BAR page...<br><br><a href="#page_0">return to home screen</a>';

    //append the new page onto the end of the body
    $('#page_body').append('<div data-role="page" id="' + page_id + '"><div data-role="content">' + string + '</div></div>');

    //initialize the new page 
    $.mobile.initializePage();

    //navigate to the new page
    $.mobile.changePage("#" + page_id, "pop", false, true);

    //add a link on the home screen to navaigate to the new page (just so nav isn't broken if user goes from new page to home screen)
    $('#page_0 div[data-role="content"]').append('<br><br><a href="#' + page_id + '">go to ' + page_id + ' page</a>');

    //refresh the home screen so new link is given proper css
    $('#page_0 div[data-role="content"]').page();
}
</script>
<title>Fixed Headers Example</title>
<script src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>

</head>

<body id="page_body">
<div data-role="page" id="page_0">
<div data-role="content">Some #page_0 text...<br><br><a href="javascript: create_page('foo_bar_page');">create new page</a></div>
</div>


</body>
</html>

回答by wezzy

To me Jasper solution doesn't work but i've found this solutionthat look cleaner and work fine

对我来说 Jasper 解决方案不起作用,但我发现这个解决方案看起来更干净而且工作正常

回答by Jasper

Here is my method for dynamically adding content to my Jquery Mobile websites:

这是我将内容动态添加到 Jquery Mobile 网站的方法:

  1. First I create a "wrapper" data-role=page div like so:

    <div data-role="page" id="my_page_id">
    <div data-role="content">
        <script>
        $('#my_page_id').live('pageshow', function() {
            my_data_loading_function('my_page_id');
        });
        </script>
    <div id="my_page_id-content"></div>
    </div><!--/content-->
    </div><!--/page-->
    
  2. Next I load data from an external source into a div tag located in my "wrapper" page:

    function my_data_loading_function(page) {
        if ($('#' + page + '-content').is(':empty')) {
            $.mobile.pageLoading();
            $('#' + page + '-content').load("my_external_script.php", function() {
                $.mobile.pageLoading(true);
                $('#' + page + '-content ul').listview();
                $('#' + page + '-content ul').page();
            });
        }
    }
    
  1. 首先,我创建一个“包装器” data-role=page div,如下所示:

    <div data-role="page" id="my_page_id">
    <div data-role="content">
        <script>
        $('#my_page_id').live('pageshow', function() {
            my_data_loading_function('my_page_id');
        });
        </script>
    <div id="my_page_id-content"></div>
    </div><!--/content-->
    </div><!--/page-->
    
  2. 接下来,我将来自外部源的数据加载到位于“包装器”页面中的 div 标签中:

    function my_data_loading_function(page) {
        if ($('#' + page + '-content').is(':empty')) {
            $.mobile.pageLoading();
            $('#' + page + '-content').load("my_external_script.php", function() {
                $.mobile.pageLoading(true);
                $('#' + page + '-content ul').listview();
                $('#' + page + '-content ul').page();
            });
        }
    }
    

Some Notes:

一些注意事项:

  • $.mobile.pageLoading(); and $.mobile.pageLoading(true); show and hide (respectively) the Jquery Mobile loading spinner.

  • if ($('#' + page + '-content').is(':empty')) { allows the user to navaigate away from the dynamically created page and then come back and not have to re-load the data until a full page refresh occurs.

  • My dynamically created page included mostly a list so listview() makes the jquery mobile framework refresh the list selected to add the proper css, page() does the same to other page elements; however you may only need to use one or the other depending on your content (or none at all if its just plain text).

  • I realize this isn't creating a whole page dynamically because the "wrapper" page is already hard-coded but if you want to add a whole new page you can probably use something like: (untested)

    $(document).append('<div data-role="page" id="my_page_id"><div data-role="content">FOO BAR</div></div>');
    $('#my_page_id').page();
    
  • $.mobile.pageLoading(); 和 $.mobile.pageLoading(true); 显示和隐藏(分别)Jquery Mobile 加载微调器。

  • if ($('#' + page + '-content').is(':empty')) { 允许用户导航离开动态创建的页面然后回来并且不必重新加载数据直到发生整页刷新。

  • 我动态创建的页面主要包括一个列表,因此 listview() 使 jquery 移动框架刷新选择的列表以添加适当的 css,page() 对其他页面元素执行相同的操作;但是,您可能只需要根据您的内容使用一个或另一个(如果只是纯文本,则根本不需要)。

  • 我意识到这不是动态创建整个页面,因为“包装器”页面已经是硬编码的,但是如果您想添加一个全新的页面,您可能可以使用以下内容:(未经测试)

    $(document).append('<div data-role="page" id="my_page_id"><div data-role="content">FOO BAR</div></div>');
    $('#my_page_id').page();
    

If you really want to make it all dynamically created you can check for window.location.hash and create your data-role=page div with the id set as the window.location.hash.

如果你真的想让它全部动态创建,你可以检查 window.location.hash 并创建你的 data-role=page div,id 设置为 window.location.hash。

Also I am using Jquery 1.6 and Jquery Mobile 1.0a4.1

我也在使用 Jquery 1.6 和 Jquery Mobile 1.0a4.1

I hope something in there can help someone out there :)

我希望那里的东西可以帮助那里的人:)

回答by sgliser

In this example on JSFiddle, I take an API call from Flickr and run the results through the jquery tmpl engine to append the new page to the to the document and then call $.mobile.changePage() to the newly inserted page. I think you'll see how useful the pairing of jquery tmpl + apis + jquery mobile is.

在 JSFiddle 上的这个示例中,我从 Flickr 调用 API 并通过 jquery tmpl 引擎运行结果以将新页面附加到文档,然后调用 $.mobile.changePage() 到新插入的页面。我想你会看到 jquery tmpl + apis + jquery mobile 的配对是多么有用。

http://jsfiddle.net/sgliser/8Yq36/5/

http://jsfiddle.net/sgliser/8Yq36/5/

回答by RyanJM

Have you looked at jquery's ajax load method? Seems like you could just have it load the page you want and replace the body each time you have a request come back.

你看过jquery的ajax加载方法吗?似乎您可以让它加载您想要的页面并在每次有请求返回时替换正文。

reference

参考