简体   繁体   English

单击一项,从其他项添加和删除类

[英]click on one item, add and remove classes from other items

I have the following HTML: 我有以下HTML:

<ul>
   <li class="one"><a href="#">one</a></li>
   <li class="two"><a href="#">two</a></li>
   <li class="three"><a href="#">three</a></li>
</ul>

<div class="one">
   Here's div one
</div>

<div class="two">
   Here's div two
</div>

<div class="three">
   Here's div three
</div>

<div class="one">
   Here's another div one, just for kicks
</div>

Here's what I want to do: when you click on the li class="one", I want to add an "active" class to all divs with class="one". 这是我要执行的操作:当您单击li class =“ one”时,我想为所有带有class =“ one”的div添加一个“ active”类。 Then when you click on li class="two", it removes the "active" from the first div and puts it on div class="two". 然后,当您单击li class =“ two”时,它将从第一个div中删除“ active”,并将其放在div class =“ two”上。 I've played around with a few different ways of doing this, but I'm having trouble coming up with an efficient way to do it for all lis and divs (there will eventually be 10 of them). 我已经尝试了几种不同的方法,但是我很难找到一种有效的方法来为所有lis和div(最终将有10种)做到这一点。

$('ul a').on('click',function(){
  $('.active').removeClass('active');
  $('div.'+$(this).text()).addClass('active');  
});

Demo: http://jsfiddle.net/9RLa9/ 演示: http//jsfiddle.net/9RLa9/

Alternatively, if you want to use the parent class instead of the text of the link to trigger your changes: 或者,如果要使用父类而不是链接的文本来触发更改,请执行以下操作:

$('ul li').on('click',function(){
  $('.active').removeClass('active');
  $('div.'+$(this).attr('class')).addClass('active');  
});

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

相关问题 单击导航项,添加类,从其他导航项中删除类-Vanilla JS - Click a nav item, add a class, remove class from other nav items - vanilla JS Vue 在循环中单击的项目上添加类并从其他项目中删除 - Vue add class on clicked item in loop and remove from other items 如果单击一个项目,删除其他项目? - if one item is clicked, remove the other items? jQuery-通过单击特定项目在输入标签中添加和删除项目 - jQuery - add and remove items in input tag, by click on the specific item 从一个 object 中删除与其他 object 项目匹配的项目 - remove items from one object those are matched with other object items 如果在其他集合中找不到项目,则从集合中删除项目 - Remove items from collection if item is not found in other collection 在单击删除/添加类。 - On click remove/add of classes. 单击图像并将 class 添加到其中,但在选择其他图像时删除 class - click an image and add class to it but when selectin other one remove the class Ionic 2:在从其他项目中删除类时向类添加类 - Ionic 2: Add Class to Item While Removing Class From Other Items 如何在默认情况下激活项目并在单击Angular中的其他项目后删除? - How to make item active by default and remove after click on other items in Angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM