Adding a “current” class to a clicked element and removing it when clicking on another element?

杀马特。学长 韩版系。学妹 提交于 2020-01-07 03:40:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!