[英]Jquery remove class and add class on clicked element
I have a div with 6 p's in it. 我有一个6 p的div。 And I start with the first p having the class "active" now when you press an other p I want that active class to be removed and added on the clicked p 现在我从第一个具有“活动”类的p开始,当您按下另一个p时,我希望该活动类被删除并添加到单击的p上
This is what I have the class is being added on the clicked p but not being removed from the other p's. 这就是我在单击的p上添加的类,但未从其他p的类上删除的类。
This is my html: 这是我的html:
<div class="slider-circles">
<p id="slide1" class="transparent-circle active"></p>
<p id="slide2" class="transparent-circle"></p>
<p id="slide3" class="transparent-circle"></p>
<p id="slide4" class="transparent-circle"></p>
<p id="slide5" class="transparent-circle"></p>
<p id="slide6" class="transparent-circle"></p>
This is my jquery 这是我的jQuery
$(".slider-circles p").click(function(e){
e.preventDefault();
if($(this).hasClass("active")){
$(this).parent().siblings().removeClass("active");
}
$(this).addClass("active");
});
Try to grab the closest .slider-circles
and find children elements with class .active
and remove that class. 尝试抓住最近的.slider-circles
并找到具有.active
类的子元素,然后删除该类。 After that just add class active
to the current element. 之后,只需将active
的类添加到当前元素。
$(".slider-circles p").click(function(e){
e.preventDefault();
$(".active", $(this).closest(".slider-circles")).removeClass("active");
$(this).addClass("active");
});
Since the p
are siblings already you should not call the .parent()
. 由于p
已经是兄弟姐妹,因此您不应调用.parent()
。
$(".slider-circles p").click(function(e){
e.preventDefault();
$(this).addClass('active').siblings().removeClass('active');
});
You just need a one liner: 您只需要一个衬板:
$(".slider-circles p").click(function(e){
e.preventDefault();
$(this).addClass("active").siblings().removeClass("active");
});
The logic will be like this - 逻辑将是这样的-
p
tag 在点击p
标签 active
class from all p
tags 您将从所有p
标签中删除active
课程 p
tag 您将向该p
标签添加类 So, in this way, you will always have clean and short code. 因此,通过这种方式,您将始终拥有简洁的代码。
$(document).ready(function() { $('.slider-circles p').click(function() { $('.slider-circles p').removeClass('active'); $(this).addClass('active'); }); });
.active { background: steelblue; color: #fff; padding: 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="slider-circles"> <p id="slide1" class="transparent-circle active">1 Para</p> <p id="slide2" class="transparent-circle">2 Para</p> <p id="slide3" class="transparent-circle">3 Para</p> <p id="slide4" class="transparent-circle">4 Para</p> <p id="slide5" class="transparent-circle">5 Para</p> <p id="slide6" class="transparent-circle">6 Para</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.