jquery-mobile

jquery-mobile - jquery mobile 1.2 0



Obligar a jQuery Mobile a reevaluar estilos/tema en contenido insertado dinĂ¡micamente (7)

Objetivo: cargar contenido HTML a través de $.ajax , insertarlo en DOM, hacer que jQuery Mobile le aplique estilos de tema.

Problema: el contenido se inserta pero carece de la temática de jQuery Mobile.

Código:

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

El HTML devuelto incluye etiquetas de data-role que jQM debe diseñar ...

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

En lugar de aplicar los estilos como debería, obtengo el siguiente error:

excepción no detectada: no hay tal método ''refresh'' para la instancia del widget de página

Sobre el código probado usando http://code.jquery.com/mobile/latest/jquery.mobile.js

Preguntas similares que me llevaron al mensaje de error anterior:

Actualice constantemente la página con los estilos adecuados de jQuery Mobile

JQM (jQueryMobile) Los elementos añadidos dinámicamente no se muestran correctamente y CSS no se aplica

jQuery Mobile: creación dinámica de elementos de formulario



Como una actualización de las respuestas proporcionadas. A partir de v1.45, puede seleccionar su contenido y usar .enhanceWithin() para mejorar los elementos secundarios.

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


Para otros que buscan una respuesta al respecto, desde el 9/9/2011 el equipo móvil de jQuery implementó esta función en una sucursal de desarrollo. Según este problema, funcionará en este señorío:

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

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


Si agrega elementos a una vista de lista, deberá llamar al método refresh () para actualizar los estilos y crear cualquier lista anidada que se agregue. Por ejemplo:

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

Si necesita generar una página dinámica, lea: " Generación de página dinámica y móvil de jQuery ". Código de muestra de este artículo:

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


Si está utilizando el método ajax para cargar contenido, así es como conseguí que funcionen el estilo y la funcionalidad móvil de jquery. Es más o menos lo mismo que la sugerencia anterior, pero para algunas personas probablemente te guste ver un ejemplo más completo.

Aquí está el código:

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



En jQuery Mobile Framework alpha4.1 y versiones anteriores, esto se hizo utilizando el método .page() .

Ejemplo para mostrar que no hay mucha diferencia:

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

Más información: http://jquerymobiledictionary.dyndns.org/faq.html

¿Por qué se presentó la nueva forma (ver la respuesta de T. Stone)? .page() se escribió con un supuesto de que el elemento DOM no se había mejorado antes.

Para desacoplar, el equipo de jQuery Mobile presenta mejoras impulsadas por eventos que no solo permitirán activar el evento, sino que también permitirán la creación de nuevos widgets para nuevos data-role sin modificar el código del método .page de JQM.