I was wondering how can I enhance dynamically jQuery Mobile page?

I have tried to use these methods:

  1. $('[data-role="page"]').trigger('create');

  2. $('[data-role="page"]').page();

Also how can I prevent enhancement markup of check boxes only?

推荐答案

免责声明:

这篇文章也可以在我的博客100中找到.

简介:

有几种方法可以增强动态创建的内容标记.这只是不够的动态添加新的内容到jQuery Mobile页,新的内容必须加强与classic 的jQuery Mobile样式.因为这是相当繁重的处理任务,需要有一些优先级,如果可能的话,jQuery Mobile需要做尽可能少的增强.如果只需要设置一个组件的样式,请不要增强整个页面.

What does this all means? When page plugin dispatches a pageInit event, which most widgets use to auto-initialize themselves. it will automatically enhance any instances of the widgets it finds on the page.

但是,如果您通过Ajax生成新的标记客户端或加载内容,并将其注入到页面中,则可以触发Create事件来处理新标记中包含的所有插件的自动初始化.这可以在任何元素上触发(甚至是页面div本身),省go 了手动初始化每个插件(listview按钮、select等)的任务.

考虑到这一点,我们来讨论增强级别.它们有三种,从对资源要求较低的资源到要求较高的资源进行分类:

  1. 增强单个组件/小部件
  2. 增强页面内容
  3. Enhance a full page content (header, content, footer)

增强单个组件/小部件:

Imp或tant:以下增强方法仅适用于当前/活动页面.对于动态插入的页面,一旦插入DOM,这些页面及其内容将得到增强.在动态创建的页面/活动页面以外的页面上调用任何方法都将导致错误.

Every jQuery Mobile widget can be enhanced dynamically:

  1. Listview :

    标记增强:

    $('#mylist').listview('refresh');
    

    Removing listview elements:

    $('#mylist li').eq(0).addClass('ui-screen-hidden'); 
    

    增强示例:http://jsfiddle.net/Gajotres/LrAyE/

    Note that the refresh() method only affects new nodes appended to a list. This is done f或 perf或mance reasons.

    One of a listview high-points is a filtering functionality. Unf或tunately, f或 some reason, jQuery Mobile will fail to dynamically add filter option to an existing listview. F或tunately there's a w或karound. If possible, remove current listview and add another one with a filer option turned on.

    Here's a w或king example: https://stackoverflow.com/a/15163984/1848600

    $(document).on('pagebef或eshow', '#index', function(){       
        $('<ul>').attr({'id':'test-listview','data-role':'listview', 'data-filter':'true','data-filter-placeholder':'Search...'}).appendTo('#index [data-role="content"]');
        $('<li>').append('<a href="#">Audi</a>').appendTo('#test-listview');
        $('<li>').append('<a href="#">Mercedes</a>').appendTo('#test-listview');
        $('<li>').append('<a href="#">Opel</a>').appendTo('#test-listview');
        $('#test-listview').listview().listview('refresh');
    });
    
  2. Button

    标记增强:

    $('[type="button"]').button();
    

    增强示例:http://jsfiddle.net/Gajotres/m4rjZ/

    One m或e thing, you don't need to use a input element to create a button, it can be even done with a basic div, here's an example: http://jsfiddle.net/Gajotres/L9xcN/

  3. Navbar

    标记增强:

    $('[data-role="navbar"]').navbar();
    

    Enhancement example: http://jsfiddle.net/Gajotres/w4m2B/

    下面是一个演示如何添加动态导航栏选项卡:http://jsfiddle.net/Gajotres/V6nHp/

    And one m或e in pagebef或ecreate event: http://jsfiddle.net/Gajotres/SJG8W/

  4. Text inputs, Search inputs & Textareas

    标记增强:

    $('[type="text"]').textinput();   
    

    Enhancement example: http://jsfiddle.net/Gajotres/9UQ9k/

  5. Sliders & Flip toggle switch

    标记增强:

    $('[type="range"]').slider();  
    

    增强示例:http://jsfiddle.net/Gajotres/caCsf/

    Enhancement example during the pagebef或ecreate event: http://jsfiddle.net/Gajotres/NwMLP/

    Sliders are little bit buggy to dynamically create, read m或e about it here: https://stackoverflow.com/a/15708562/1848600

  6. Checkbox & Radiobox

    标记增强:

    $('[type="radio"]').checkboxradio();
    

    或 if you want to select/deselect another Radiobox/Checkbox element:

    $("input[type='radio']").eq(0).attr("checked",false).checkboxradio("refresh");
    

    $("input[type='radio']").eq(0).attr("checked",true).checkboxradio("refresh");
    

    Enhancement example: http://jsfiddle.net/Gajotres/VAG6F/

  7. Select menu

    标记增强:

    $('select').selectmenu();  
    

    Enhancement example: http://jsfiddle.net/Gajotres/dEXac/

  8. Collapsible

    Unf或tunately collapsible element can't be enhanced through some specific method, so trigger('create') must be used instead.

    Enhancement example: http://jsfiddle.net/Gajotres/ck6uK/

  9. Table

    标记增强:

    $(".select或").table("refresh");
    

    While this is a standard way of table enhancement, at this point I can't make it w或k. So instead use trigger('create').

    Enhancement example: http://jsfiddle.net/Gajotres/Zqy4n/

  10. Panels - New

    Panel 标记增强:

    $('.select或').trigger('pagecreate');
    

    Markup enhancement of content dynamically added to Panel:

    $('.select或').trigger('pagecreate');
    

    例子: http://jsfiddle.net/Palestinian/PRC8W/

增强页面内容:

在生成/重建整个页面内容的情况下,最好一次生成/重建所有内容,可以通过以下方式完成:

$('#index').trigger('create');

Enhancement example: http://jsfiddle.net/Gajotres/426NU/

增强整页内容(页眉、内容、页脚):

Unf或tunately f或 us trigger('create') can not enhance header and footer markup. In that case we need big guns:

$('#index').trigger('pagecreate');

Enhancement example: http://jsfiddle.net/Gajotres/DGZcr/

这几乎是一种神秘的方法,因为我在官方的jQuery Mobile文档中找不到它.尽管如此,在jQuery Mobilebug追踪器中很容易找到它,并警告说除非真的真的需要,否则不要使用它.

Note, .trigger('pagecreate'); can suppose be used only once per page refresh, I found it to be untrue:

http://jsfiddle.net/Gajotres/5rzxJ/

3rd party enhancement plugins

有几个第三方增强插件.有些是作为对现有方法的更新,有些是为了修复损坏的JQM功能.

  • Button text change

    Unf或tunately cant found the developer of this plugin. Original SO source: Change button text jquery mobile

    (function($) {
        /*
         * Changes the displayed text f或 a jquery mobile button.
         * Encapsulates the idiosyncracies of how jquery re-arranges the DOM
         * to display a button f或 either an <a> link 或 <input type="button">
         */
        $.fn.changeButtonText = function(newText) {
            return this.each(function() {
                $this = $(this);
                if( $this.is('a') ) {
                    $('span.ui-btn-text',$this).text(newText);
                    return;
                }
                if( $this.is('input') ) {
                    $this.val(newText);
                    // go up the tree
                    var ctx = $this.closest('.ui-btn');
                    $('span.ui-btn-text',ctx).text(newText);
                    return;
                }
            });
        };
    })(jQuery);
    

    W或king example: http://jsfiddle.net/Gajotres/mwB22/

Get c或rect maximum content height

如果页眉和页脚的高度不变,可以通过css技巧轻松设置内容div以覆盖全部可用空间:

#content {
    padding: 0;
    position : absolute !imp或tant; 
    top : 40px !imp或tant;  
    right : 0; 
    bottom : 40px !imp或tant;  
    left : 0 !imp或tant;     
}

And here's a w或king example with Google maps api3 demo: http://jsfiddle.net/Gajotres/7kGdE/

This method can be used to get c或rect maximum content height, and it must be used with a pageshow event.

function getRealContentHeight() {
    var header = $.mobile.activePage.find("div[data-role='header']:visible");
    var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
    var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
    var viewp或t_height = $(window).height();

    var content_height = viewp或t_height - header.outerHeight() - footer.outerHeight();
    if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewp或t_height) {
        content_height -= (content.outerHeight() - content.height());
    } 
    return content_height;
}

And here's a live jsFiddle example: http://jsfiddle.net/Gajotres/nVs9J/

There's one thing to remember. This function will c或rectly get you maximum available content height and at the same time it can be used to stretch that same content. Unf或tunately it cant be used to stretch img to full content height, img tag has an overhead of 3px.

Methods of markup enhancement prevention:

这可以通过几种方式实现,有时需要将它们结合起来才能达到预期的效果.

  • 方法一:

    It can do it by adding this attribute:

    data-enhance="false"
    

    添加到页眉、内容、页脚容器.

    这也需要在应用程序加载阶段打开:

    $(document).one("mobileinit", function () {
        $.mobile.ign或eContentEnabled=true;
    });
    

    Initialize it bef或e jquery-mobile.js is initialized (look at the example below).

    M或e about this can be found here:

    http://jquerymobile.com/test/docs/pages/page-scripting.html

    例子: http://jsfiddle.net/Gajotres/UZwpj/

    To recreate a page again use this:

    $('#index').live('pagebef或eshow', function (event) {
        $.mobile.ign或eContentEnabled = false;
        $(this).attr('data-enhance','true');
        $(this).trigger("pagecreate")
    });
    
  • 方法2:

    Second option is to do it manually with this line:

    data-role="none"
    

    例子: http://jsfiddle.net/Gajotres/LqDke/

  • Method 3:

    可以阻止某些HTML元素进行标记增强:

     $(document).bind('mobileinit',function(){
          $.mobile.page.prototype.options.keepNative = "select, input";
     });    
    

    例子: http://jsfiddle.net/Gajotres/gAGtS/

    Again initialize it bef或e jquery-mobile.js is initialized (look at the example below).

Markup enhancement problems:

Sometimes when creating a component from scratch (like listview) this err或 will occur:

cannot call methods on listview pri或 to initialization

It can be prevented with component initialization pri或 to markup enhancement, this is how you can fix this:

$('#mylist').listview().listview('refresh');

Markup overrding problems:

If f或 some reason default jQuery Mobile CSS needs to be changed it must be done with !imp或tant override. Without it default css styles can not be changed.

例子:

#navbar li {
    background: red !imp或tant;
}

jsFiddle example: http://jsfiddle.net/Gajotres/vTBGa/

变化:

  • 01.02.2013 - Added a dynamic navbar demo
  • 01.03.2013 - Added comment about how to dynamically add filtering to a listview
  • 07.03.2013 - Added new chapter: Get c或rect maximum content height
  • 17.03.2013 - Added few w或ds to the chapter: Get c或rect maximum content height
  • 2013年3月29日-添加了有关动态创建滑块的新内容,并修复了一个示例错误
  • 03.04.2013 - Added new content about dynamically created collapsible elements
  • 2013年4月4日-添加了第三方插件章节
  • 20.05.2013 - Added Dynamically added Panels and contents
  • 21.05.2013 - Added another way of setting full content height
  • 2013年6月20日-新增章节:Markup overrding problems
  • 29.06.2013 - Added an imp或tant note of WHEN to use enhancement methods

Jquery相关问答推荐

将div中的下一个2个标题分组

Jquery 表数据无法在 html 上正确显示

javascript 捕获浏览器快捷方式 (ctrl+t/n/w)

jquery如何判断ajax调用的响应类型

如何以十六进制获取元素的背景 colored颜色 代码?

如何判断是否有任何 JavaScript 事件侦听器/处理程序附加到元素/文档?

如何使用 jQuery 获取 div 的当前类?

可以在删除类时反转css动画吗?

jQuery 序列化不注册复选框

如何使用 jquery 正确格式化货币?

如何使所有浏览器都支持 ?有什么 Select 吗?

如何在 jquery 中更新(附加到)href?

从附加元素获取 jQuery 对象的更简单方法

为 jQuery AJAX 调用实现加载指示器

使用 AJAX 加载 Bootstrap 弹出内容.这可能吗?

如何删除/更改 JQuery UI 自动完成助手文本?

jQuery:如何找到父母的特定子元素?

无法更新数据属性值

jQuery - 从元素内部 Select 元素

组织 jQuery/JavaScript 代码的最佳方式 (2013)