admin管理员组

文章数量:1287856

Forgive me for being a noob, but shouldn't this work?

$(document).ready(function() {
    $('.button').click(function() {
       $(this).addClass('button-clicked');
    });

    $('.button-clicked').click(function() {
        $(this).removeClass('button-clicked');
    });

});

Shouldn't the second click remove the class and take it back to .button?

Here it is on jsfiddle: /

Forgive me for being a noob, but shouldn't this work?

$(document).ready(function() {
    $('.button').click(function() {
       $(this).addClass('button-clicked');
    });

    $('.button-clicked').click(function() {
        $(this).removeClass('button-clicked');
    });

});

Shouldn't the second click remove the class and take it back to .button?

Here it is on jsfiddle: http://jsfiddle/pXdwM/

Share Improve this question edited Dec 9, 2010 at 7:08 Yi Jiang 50.2k16 gold badges138 silver badges136 bronze badges asked Dec 9, 2010 at 7:00 izolateizolate 1,6004 gold badges22 silver badges37 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

no, because at the point you're calling the second click() the button doesn't have ".button-clicked" and therefore event handler is not assigned. You could rewrite it like this

$('.button').click(function() {
   $(this).toggleClass('button-clicked');
});

or use live()

$('.button-clicked').live("click", function() {
    $(this).removeClass('button-clicked');
});

You are adding an event to each element with class '.button-clicked', but the class does not apply until you actually click. So you need to move the second listener into the first callback, or use the toggleClass function:

$('.button').click(function() {
   $(this).toggleClass('button-clicked');
});

本文标签: javascriptremoveClass doesn39t work how addClass doesStack Overflow