سؤال

I'm trying to toggle a class on a single button, where the class would be dynamically assigned based on a state. Here is my code:

$('body').on('click', '.button', function () {
    var $itm = $(this).children(".icon");
    if ($itm.hasClass('hide')) {
        $itm.toggleClass('unhide', 'hide')
    } else {
        $itm.toggleClass('hide', 'unhide')
    }
});

What I'm trying to achieve is this: If a button has class .hide, the onclick toggles this class to .unhide, and vice versa.

So far the only time class toggling works is, is on the second click. The first click does not change anything.

هل كانت مفيدة؟

المحلول

.toggleClass accepts one or more class names separated by a space like this:

$('body').on('click', '.button', function () {
    $(this).children(".icon").toggleClass("hide unhide");
});

Working example (with a tweak to your HTML): http://jsfiddle.net/jfriend00/9tV33/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top