Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I re-render dynamically generated anchor tags in jquery Mobile?

I get an anchor tag snippet html from the server on ajax call. How do I "refresh" so that jquery mobile can append the necessary classes to the links?

For example the link that jquery mobile generates has a ui-link:

<a class="ui-link" href="http://www.google.com">http://www.google.com</a>

How do I ensure that the correct styles are appended on a newly generated anchor tag?

like image 431
unj2 Avatar asked Nov 14 '22 08:11

unj2


1 Answers

If you want to refresh a widget that has already been initialized then you can refresh each type of widget using it's respective function:

$('.ui-btn').button('refresh');

Notice I used the .ui-btn class to select the button elements, this class is added once the button is initialized, so you can be sure that you are refreshing an already initialized button widget.

Docs: http://jquerymobile.com/demos/1.1.0-rc.1/docs/buttons/buttons-methods.html

If you need to initialize a widget that has yet to be initialized, then you just omit the 'refresh' or use .trigger('create'):

$('[data-role="button"], button, input[type="button"], input[type="submit"]').not('.ui-btn').button();//or .trigger('create');

Notice here I omit the already initialized widgets by using .not('.ui-btn') so this will only initialize un-initialized widgets. If you try to initialize a widget that has already been initialized then you get an error (same if you try to refresh a widget that hasn't been initialized yet).

Update

If your HTML is being outputted by the server then you can initialize the widgets before adding them to the DOM:

$.ajax({
    ...
    success : function (serverResponse) {
        var $out = $(serverResponse);
        //if there is a container with elements inside it, use `.find()`,
        //if all the elements are siblings at the top level then use `.filter()`
        $out.find('a').button();
        $('body').append($out);
    }
});

You can also use the .buttonMarkup() function to update button widgets: http://jquerymobile.com/demos/1.1.0-rc.1/docs/buttons/buttons-options.html

like image 55
Jasper Avatar answered Dec 06 '22 14:12

Jasper