问题
I am trying to add a class of "current" to a div with jQuery and then remove the class when a different div is clicked. So far I have the "current" class being added, but I am not sure how to remove the "current" class from that div and apply it to the new div that is clicked.
Here's the Javascript:
$(document).ready(function() {
$('#images div').click(function() {
$(this).addClass('current');
$('.bios .active').hide().removeClass('active');
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
Here's the HTML:
<div id="images">
<div><div class="name">Name 1</div></div>
<div><div class="name">Name 2</div></div>
<div><div class="name">Name 3</div></div>
</div>
<div class="bios">
<div>Bio 1</div>
<div>Bio 2</div>
<div>Bio 3</div>
</div>
So I just want the "current" class to be applied to the image in the div that's being clicked and to remove the class from any previous divs that may have had it. Thank you.
回答1:
Just remove the class on all it's siblings, as being specific avoids confusion when you decide to use .current
somewhere else in the DOM.
$(document).ready(function() {
$('#images div').on('click', function() {
$(this).addClass('current').siblings().removeClass('current');
$('.bios .active').hide().removeClass('active');
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
回答2:
$(document).ready(function() {
$('#images div').click(function() {
$('.current').removeClass('current');
$(this).addClass('current');
$('.bios .active').hide().removeClass('active');
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
回答3:
You could remove all of the current classes before adding it.
$(document).ready(function() {
$('#images div').click(function() {
$('.current').removeClass('current');
$(this).addClass('current');
$('.bios .active').hide();
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
But the performance will be better if you keep track of the current one and then remove it.
$(document).ready(function() {
var $current;
$('#images div').click(function() {
if($current) $current.removeClass('current');
$current = $(this);
$current.addClass('current');
$('.bios .active').hide();
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
回答4:
Just add $('#images div.current').removeClass('current');
before doing $(this).addClass('current');
来源:https://stackoverflow.com/questions/22483010/adding-a-current-class-to-a-clicked-element-and-removing-it-when-clicking-on-a