【问题标题】:Forcing jQuery Mobile to re-evaluate styles/theme on dynamically inserted content强制 jQuery Mobile 重新评估动态插入内容的样式/主题
【发布时间】:2011-09-11 22:51:45
【问题描述】:

目标:通过$.ajax加载HTML内容,将其插入DOM,让jQuery Mobile为其应用主题样式。

问题:内容已插入,但缺少 jQuery Mobile 主题。

代码:

$.ajax({
    ...
    success: function(html) {
        $('#container').append(html);
        $('#page').page('refresh', true);
    }
});

返回的 HTML 包含 jQM 应该设置样式的 data-role 标记...

<a data-role="button">Do Something</a>

我没有应用应有的样式,而是收到以下错误:

未捕获的异常:没有这样的方法 页面小部件实例的“刷新”


以上代码使用http://code.jquery.com/mobile/latest/jquery.mobile.js测试


类似的问题让我看到上述错误消息:

Consistently update page with appropriate jQuery Mobile styles

JQM (jQueryMobile) Dynamically added elements not displaying correctly and CSS is not applied

jQuery Mobile - Dynamically creating form elements

【问题讨论】:

  • 我尝试在要加载的文档末尾添加 .trigger("create") JS;效果很好。

标签: jquery-mobile


【解决方案1】:

刚刚得到一个类似问题的答案,尝试使用

.trigger("create")

在获取添加内容的元素上。

请看这里:jQuery Mobile does not apply styles after dynamically adding content

【讨论】:

  • 截至本文发表之日,这对我有用,其中 .page() 并不总是有效。
  • 我必须向上移动一个级别才能使其正常工作 - 所以我在我注入的列表视图上方的 div 上调用了触发器。谢谢你,我花了半天时间弄乱 .listview 没有成功
  • 这可行,但一直是deprecated as of jQuery 1.4。使用 .enhanceWithin() 代替。
【解决方案2】:

如果您将项目添加到列表视图,则需要对其调用 refresh() 方法来更新样式并创建任何添加的嵌套列表。例如:

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

如果需要渲染动态页面,请阅读:“jQuery Mobile and Dynamic Page Generation”。本文示例代码:

// Load the data for a specific category, based on
// the URL passed in. Generate markup for the items in the
// category, inject it into an embedded page, and then make
// that page the current active page.
function showCategory( urlObj, options )
{
    var categoryName = urlObj.hash.replace( /.*category=/, "" ),

        // Get the object that represents the category we
        // are interested in. Note, that at this point we could
        // instead fire off an ajax request to fetch the data, but
        // for the purposes of this sample, it's already in memory.
        category = categoryData[ categoryName ],

        // The pages we use to display our content are already in
        // the DOM. The id of the page we are going to write our
        // content into is specified in the hash before the '?'.
        pageSelector = urlObj.hash.replace( /\?.*$/, "" );

    if ( category ) {
        // Get the page we are going to dump our content into.
        var $page = $( pageSelector ),

            // Get the header for the page.
            $header = $page.children( ":jqmData(role=header)" ),

            // Get the content area element for the page.
            $content = $page.children( ":jqmData(role=content)" ),

            // The markup we are going to inject into the content
            // area of the page.
            markup = "<p>" + category.description + "</p><ul data-role='listview' data-inset='true'>",

            // The array of items for this category.
            cItems = category.items,

            // The number of items in the category.
            numItems = cItems.length;

        // Generate a list item for each item in the category
        // and add it to our markup.
        for ( var i = 0; i < numItems; i++ ) {
            markup += "<li>" + cItems[i].name + "</li>";
        }
        markup += "</ul>";

        // Find the h1 element in our header and inject the name of
        // the category into it.
        $header.find( "h1" ).html( category.name );

        // Inject the category items markup into the content element.
        $content.html( markup );

        // Pages are lazily enhanced. We call page() on the page
        // element to make sure it is always enhanced before we
        // attempt to enhance the listview markup we just injected.
        // Subsequent calls to page() are ignored since a page/widget
        // can only be enhanced once.
        $page.page();

        // Enhance the listview we just injected.
        $content.find( ":jqmData(role=listview)" ).listview();

        // We don't want the data-url of the page we just modified
        // to be the url that shows up in the browser's location field,
        // so set the dataUrl option to the URL for the category
        // we just loaded.
        options.dataUrl = urlObj.href;

        // Now call changePage() and tell it to switch to
        // the page we just modified.
        $.mobile.changePage( $page, options );
    }
}

【讨论】:

    【解决方案3】:

    如果您使用 ajax 方法加载到内容中,这就是我让样式和 jquery 移动功能工作的方式。这与上面的建议几乎相同,但对于某些人来说,您可能希望看到更完整的示例。

    代码如下:

    $.ajax({
    url: 'url.php',
    success: function(data) {    
    $("#div").html(data).trigger('create');
    }
    });
    

    【讨论】:

    • 这是我见过的唯一一个选择器不是 $('#myListView') 之类的东西,而是父 div 的例子。在我的情况下,我的 ul-listview 是从 ajax 调用返回的,并且执行 $("#div").html(data) 会获取数据,但随后在 listview 上调用 .trigger 不会做任何事情。我不认为调用 $("#div").trigger('create'),但就像你的示例一样,似乎有效。多么奇怪。谢谢!我花了几个小时在这上面。
    【解决方案4】:

    作为对所提供答案的更新。从 v1.45 开始,您可以选择您的内容并使用 .enhanceWithin() 来增强子元素。

    http://api.jquerymobile.com/enhanceWithin/

    【讨论】:

    • 这可以在 ASP.Net 中的异步回发之后使用,例如带有更新面板。效果很好。
    【解决方案5】:

    在 jQuery Mobile Framework alpha4.1 及更早版本中这是通过使用.page() 方法完成的。

    显示没有太大区别的示例:

    $( ... lots of HTML ...).appendTo(".ui-content").page();
    

    更多信息:http://jquerymobiledictionary.dyndns.org/faq.html

    为什么要引入新方法(参见 T. Stone 的回答)? .page() 是在假设 DOM 元素之前未增强的情况下编写的。

    为了解耦,jQuery Mobile 团队引入了事件驱动增强功能,不仅允许触发事件,而且还可以在不修改 JQM .page 方法的代码的情况下为新的data-roles 创建新的小部件。

    【讨论】:

      【解决方案6】:

      $('.selector').trigger('create'); 似乎是最好的方法,请参阅下面的官方常见问题解答:

      http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php

      【讨论】:

        【解决方案7】:

        对于寻找此问题的答案的其他人,截至 2011 年 6 月 9 日,jQuery 移动团队已在开发分支中实现了此功能。根据这个问题,它将在这个庄园工作:

        $(".ui-content").append( ... lots of HTML ...).trigger( "enhance" );

        https://github.com/jquery/jquery-mobile/issues/1799

        【讨论】:

        • 这还为时过早。我了解您想成为第一个发布此功能的人,但代码尚未发布,如果您不提供有关具有此功能的版本的任何信息,可能会造成很多混乱。
        猜你喜欢
        • 2012-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-11
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        相关资源
        最近更新 更多