简体   繁体   English

jQuery:如果存在类,请将其删除,然后将其添加到新元素中

[英]jQuery: If class exists, remove it, then add it to new element

I'm working on an accordion style video section. 我正在研究手风琴风格的视频部分。 I'm currently trying to check if a class exists on click. 我目前正在尝试检查单击是否存在一个类。 I want it to only open 1 section at a time, so I need to 我希望它一次只能打开一个部分,所以我需要

  1. Check if the class exists on click 单击单击检查类是否存在
  2. If it does, remove class 如果是这样,请删除课程
  3. Add class to the clicked element 将类添加到单击的元素

I tried doing this with just addClass(); 我尝试使用addClass(); and toggleClass(); toggleClass(); but am not 100% sure on what I'm missing. 但是我不确定100%缺少什么。

Add Class 新增课程

$(".contents-row").click(function(){
    $(this).toggleClass("content-open");
}); 

Toggle Class 切换类

$('.contents-row').click(function(){
    $(this).toggleClass('content-open');
});

This is the basic HTML set up 这是基本的HTML设置

<div class="contents-row">
    <div class="content-option press">
        <div class="class-section-title">test1</div>
    </div>
    <div class="drop">
        test 1
    </div>
</div>

A full version of the drop down in on JSFiddle . JSFiddle上下拉菜单的完整版本。

Thanks for the help! 谢谢您的帮助!

First remove content-open class from all elements having content-open class. 首先从具有content-open类的所有元素中删除content-open content-open类。 Then add the class to clicked element like following. 然后将类添加到clicked元素,如下所示。

$('.contents-row').click(function(){
    $('.content-open').removeClass('content-open');
    $(this).addClass('content-open');
});

You need to remove the class content-open from all div with class contents-row first and then add to the currently clicked div . 您需要先从所有div删除类content-open ,然后再将其添加到当前单击的div ,其中所有类都应具有class contents-row

$('.contents-row').click(function(){
    $('.contents-row').removeClass('content-open');
    $(this).toggleClass('content-open');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM