简体   繁体   中英

Change data-theme in jQuery mobile

I'd like to provide my user some persistent feedback after they've pressed a button (like it's indented or something). I tried:

$(this).data('theme','b');

But that doesn't work.

Q: Is there a way to show an indented button, or change it's data-theme on the fly?

I know this is an old question, but I just recently ran into this hurdle myself.

The correct way of doing this would be as follows:

$(this).buttonMarkup({theme: 'b'});

I have been looking for a way to dynamically change the theme globally in jQuery Mobile (eg on a button click). Turned out to be more complex than I imagined to do this. Anyway, here is my take on this, inspired by various solutions on SO and other sites:

// Dynamically changes the theme of all UI elements on all pages,
// also pages not yet rendered (enhanced) by jQuery Mobile.
$.mobile.changeGlobalTheme = function(theme)
{
    // These themes will be cleared, add more
    // swatch letters as needed.
    var themes = " a b c d e";

    // Updates the theme for all elements that match the
    // CSS selector with the specified theme class.
    function setTheme(cssSelector, themeClass, theme)
    {
        $(cssSelector)
            .removeClass(themes.split(" ").join(" " + themeClass + "-"))
            .addClass(themeClass + "-" + theme)
            .attr("data-theme", theme);
    }

    // Add more selectors/theme classes as needed.
    setTheme(".ui-mobile-viewport", "ui-overlay", theme);
    setTheme("[data-role='page']", "ui-body", theme);
    setTheme("[data-role='header']", "ui-bar", theme);
    setTheme("[data-role='listview'] > li", "ui-bar", theme);
    setTheme(".ui-btn", "ui-btn-up", theme);
    setTheme(".ui-btn", "ui-btn-hover", theme);
};

There is some additional complexity involved because I also wanted to update the theme of pages not yet shown by JQM. Structuring the code in pairs of selectors and theme classes helped making this more clear to me.

You can call this function to update the theme for all UI elements dynamically, for example:

$.mobile.changeGlobalTheme("b");

I also like the solutions I have seen that use regular expressions, but in this case I prefer the approach to explicitly state selectors and theme classes because of the clarity and ease of adding new items. I figured out the selector/class pairs by inspecting the DOM tree.

I must say I appreciate the Lisp-like flavour of modern JavaScript code.

Maybe this is usefull to you: change jquery mobile color swatch dynamically

I think it can be done with buttons the same way.

For a submit button inside a form, this worked for me using jQuery Mobile 1.2.0:

$(this).buttonMarkup({theme: 'b'});
$(this).parent().buttonMarkup({ theme: "b" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM