Принуждение jQuery Mobile к повторной оценке стилей / тем на динамически вставляемом контенте - PullRequest
55 голосов
/ 09 июня 2011

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

Проблема: Контент получаетвставлен, но отсутствует тематика jQuery Mobile.

Код:

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

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

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

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

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


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


Подобные вопросы, которые привели меня к приведенному выше сообщению об ошибке:

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

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

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

Ответы [ 7 ]

66 голосов
/ 03 ноября 2011

Только что получил ответ на аналогичный вопрос, попробуйте использовать

.trigger("create")

для элемента, к которому добавляется контент.

См. Здесь: jQuery Mobile не применяетсястили после динамического добавления контента

12 голосов
/ 05 февраля 2013

Если вы добавляете элементы в просмотр списка, вам необходимо вызвать для него метод 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'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 );
    }
}
10 голосов
/ 17 апреля 2012

Если вы используете метод ajax для загрузки в контент, вот как я получил работу со стилем и мобильными функциями jquery. Это в значительной степени совпадает с предложением выше, но для некоторых людей вам, вероятно, нравится смотреть более полный пример.

Вот код:

$.ajax({
url: 'url.php',
success: function(data) {    
$("#div").html(data).trigger('create');
}
});
4 голосов
/ 04 декабря 2014

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

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

1 голос
/ 24 августа 2013

$('.selector').trigger('create'); кажется наилучшим подходом, смотрите официальный FAQ ниже:

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

1 голос
/ 10 июня 2011

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

Пример, показывающий, что разница невелика:

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

Подробнее: http://jquerymobiledictionary.dyndns.org/faq.html

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

Ради разъединения команда jQuery Mobile представляет управляемое событиями усовершенствование, которое не только позволит инициировать событие, но и сделает возможным создание новых виджетов для новых data-role без изменения кода JQM.метод страницы.

0 голосов
/ 09 июня 2011

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

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

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

...