[英]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');
});
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.