添加“当前"消息.类为一个单击的元素,并在单击另一个元素时将其删除? [英] Adding a "current" class to a clicked element and removing it when clicking on another element?

查看:96
本文介绍了添加“当前"消息.类为一个单击的元素,并在单击另一个元素时将其删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery将当前"类添加到div,然后在单击不同的div时删除该类.到目前为止,我已经添加了当前"类,但是我不确定如何从该div中删除当前"类并将其应用于单击的新div.

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.

这是Javascript:

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');
  });
});

这是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>

因此,我只希望将当前"类应用于要单击的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.

推荐答案

只需删除类中的所有同级类,因为当您决定在DOM中的其他位置使用.current时,应避免混淆.

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');
    });
});

这篇关于添加“当前"消息.类为一个单击的元素,并在单击另一个元素时将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆