IT story

jQuery Mobile이 동적으로 삽입 된 콘텐츠의 스타일 / 테마를 재평가하도록 강제

hot-time 2021. 1. 7. 20:03
반응형

jQuery Mobile이 동적으로 삽입 된 콘텐츠의 스타일 / 테마를 재평가하도록 강제


목표 : 를 통해 HTML 콘텐츠를로드 $.ajax하고, DOM에 삽입하고, jQuery Mobile이 테마 스타일을 적용하도록합니다.

문제 : 콘텐츠가 삽입되지만 jQuery Mobile 테마가 없습니다.

암호:

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

반환 된 HTML에는 data-rolejQM이 스타일을 지정해야하는 태그가 포함됩니다 .

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

스타일을 적용하는 대신 다음과 같은 오류가 발생합니다.

포착되지 않은 예외 : 페이지 위젯 인스턴스에 대해 '새로 고침'메소드가 없습니다.


위의 코드는 http://code.jquery.com/mobile/latest/jquery.mobile.js


위의 오류 메시지가 표시되는 유사한 질문 :

적절한 jQuery Mobile 스타일로 페이지를 일관되게 업데이트

JQM (jQueryMobile) 동적으로 추가 된 요소가 올바르게 표시되지 않고 CSS가 적용되지 않음

jQuery Mobile-동적으로 양식 요소 생성


비슷한 질문에 대한 답을 얻었습니다.

.trigger("create")

콘텐츠가 추가되는 요소에

여기를보십시오 : jQuery Mobile은 콘텐츠를 동적으로 추가 한 후 스타일을 적용하지 않습니다.


목록보기에 항목을 추가하는 경우 해당 항목에서 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 );
    }
}

콘텐츠에로드하기 위해 ajax 메서드를 사용하는 경우 이것이 스타일링 및 jquery 모바일 기능이 작동하는 방법입니다. 위의 제안과 거의 동일하지만 일부 사람들에게는 더 완전한 예를보고 싶을 것입니다.

다음은 코드입니다.

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

As an update to the answers provided. As of v1.45 you can select your content and use .enhanceWithin() to enhance the child elements.

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


In jQuery Mobile Framework alpha4.1 and earlier this was done by using the .page() method.

Example to show there's not much of a difference:

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

More info: http://jquerymobiledictionary.dyndns.org/faq.html

Why the new way (see T. Stone's answer) was introduced? .page() was written with an assumprion that the DOM element was not enhanced before.

For the sake of decoupling tje jQuery Mobile team introduces event-driven enhancement that will not only allow triggering the event, but also will make creating new widgets for new data-roles possible without modifying the code of JQM's .page method.


$('.selector').trigger('create'); seems to be the best approach, see the official FAQ below:

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


For others searching for an answer for this, as of 6/9/2011 the jQuery mobile team has implemented this feature in a development branch. According to this issue, it will work in this manor:

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

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

ReferenceURL : https://stackoverflow.com/questions/6297470/forcing-jquery-mobile-to-re-evaluate-styles-theme-on-dynamically-inserted-conten

반응형