问题
http://jsfiddle.net/freqn/ZHt6V/2/
How do I remove class from previous selection when clicking additonal item in this accordion? I want the class to be removed from the previous clicked item when the next item is expanded. All other items should turn back to gray when new item is selected. Thank you.
(function () {
$('dd').hide();
$('dt').click(function(){
$(this)
.next()
.slideToggle(200)
.siblings('dd')
.slideUp(200);
});
$('dt').click(function(){
$(this).toggleClass('active');
});
})();
回答1:
Edit: http://jsfiddle.net/uptownapps/ZHt6V/5/ -- Revision to add collapse functionality.
http://jsfiddle.net/uptownapps/ZHt6V/4/
First you can use the same click function to handle all of this. Also, I prefer to use removeClass
and addClass
rather than toggleClass
just because I am able to keep track of what's happening in my head better that way.
(function () {
$('dt').click(function(){
$(this) .next()
.slideToggle(200)
.siblings('dd')
.slideUp(200);
$('.active').removeClass('active');
$(this).addClass('active');
});
})();
You'll notice I also removed the $('dd').hide();
and instead added display: none;
to the CSS definition for the dd
element. This will fix the "flash" you see when the page loads before jQuery and your JS has run.
来源:https://stackoverflow.com/questions/20025799/how-do-i-remove-class-from-previous-selection-when-clicking-additional-item