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.net/pXdwM/
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');
});
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.