1

What's the proper way to toggle a couple classes on click in jQuery?

1) HTML before click:

<button class="btn"><i class="icon-sign-blank"></i> Click me!</button>

2) HTML after click:

<button class="btn btn-success"><i class="icon-check"></i> Clicked!</button>

3) HTML after another click: (same as beginning)

<button class="btn"><i class="icon-sign-blank"></i> Click me!</button>

Current jQuery:

$('btn').on('click',function(e) {
    $('btn > i').removeClass('icon-sign-blank').addClass('icon-check');
    $('btn').addClass('btn-success');
});

But this works once, but not back again. What's the proper way to handle both directions?

4

3 回答 3

5

您可以 - 应该 - 使用 toggleClass 来管理它!

$('btn').on('click',function(e) {
    $('btn > i').toggleClass('icon-sign-blank icon-check');
    $(this).toggleClass('btn-success');
});
于 2013-04-19T21:13:43.513 回答
1

jQuery 的toggleClass函数。

于 2013-04-19T21:13:05.637 回答
0

...并且不使用toggleClass(如果您不想使用 jQuery,也可以不使用 jQuery 来完成)

var btnEl = $('btn');
btnEl.on('click', function() {
    if (btnEl.hasClass('icon-sign-blank')) btnEl.removeClass('icon-sign-blank');
    else btnEl.addClass('icon-sign-blank');
});
于 2013-04-19T21:13:34.717 回答