Подтвердить что ты не робот

Принуждение jQuery Mobile для переоценки стилей/темы на динамически вставленном контенте

Цель: Загружать содержимое HTML через $.ajax, вставлять его в DOM, использовать jQuery Mobile для использования стилей темы.

Проблема: Содержимое вставлено, но отсутствует jQuery Mobile theming.

Код:

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

В HTML возвращается теги data-role, которые jQM должен стилизовать...

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

Вместо применения стилей, как и должно, я получаю следующую ошибку:

исключение uncaught: нет такого метода 'refresh' для экземпляра виджета страницы


Выше кода с использованием http://code.jquery.com/mobile/latest/jquery.mobile.js


Аналогичные вопросы, которые привели меня к указанному выше сообщению об ошибке:

Последовательно обновлять страницу с помощью соответствующих стилей jQuery Mobile

JQM (jQueryMobile) Динамически добавленные элементы не отображаются правильно, а CSS не применяется

jQuery Mobile - Динамическое создание элементов формы

4b9b3361

Ответ 2

Если вы добавляете элементы в список, вам нужно вызвать метод refresh() для обновления стилей и создания любых вложенных списков, которые будут добавлены. Например:

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

Если вам нужно отобразить динамическую страницу, прочитайте: "jQuery Mobile и динамическое создание страниц". Пример кода из этой статьи:

// 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 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 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');
}
});

Ответ 4

Как обновление предоставленных ответов. Начиная с версии 1.45 вы можете выбрать свой контент и использовать .enhanceWithin() для улучшения дочерних элементов.

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

Ответ 5

В jQuery Mobile Framework alpha4.1 и ранее это было выполнено с помощью метода .page().

Пример, чтобы показать, что разница не очень большая:

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

Дополнительная информация: http://jquerymobiledictionary.dyndns.org/faq.html

Почему появился новый способ (см. ответ Т. Стоуна)? .page() был написан с предположением, что элемент DOM ранее не был расширен.

Для развязки tje Команда jQuery Mobile вводит усовершенствование, управляемое событиями, которое позволит не только запускать событие, но и сделать возможным создание новых виджетов для нового data-role без изменения кода JQM.page method.

Ответ 7

Для других, которые ищут ответ для этого, с 6/9/2011 команда мобильных jQuery реализовала эту функцию в ветке разработки. Согласно этой проблеме, он будет работать в этой усадьбе:

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

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