문제

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