[英]Toggle/add/remove class in Jquery not working as expected
In my code i have two boxes, i want when i click on the box it should gain some width and when i click on another box it should gain the width and remove the extra width from previous box. 在我的代码中,我有两个框,我想当我单击框时应该获得一些宽度,而当我单击另一个框时应该获得宽度并从上一个框中删除多余的宽度。 I have done this successfully but when i click the extra width box again it does not removing it's extra width.
我已成功完成此操作,但是当我再次单击额外宽度框时,它并没有删除它的额外宽度。
$('.dos').click(function() { $(this).toggleClass('clicked'); }); $('.dos').click(function() { $('.dos').removeClass('clicked'); $(this).addClass('clicked'); });
#box { width: 100px; height: 100px; border: 1px solid #ccc; transition: width 1s; } #box.clicked { width: 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box" class="dos"></div> <div id="box" class="dos"></div>
Just want toggle class should also work with addClass
and removeClass
只希望切换类也可以与
addClass
和removeClass
( Demo on jsfiddle.net ) ( jsfiddle.net上的演示 )
Check the updated fiddle and try 检查更新的小提琴并尝试
$(this).toggleClass('clicked').siblings().removeClass('clicked');
Demo 演示版
$('.dos').click(function() { $(this).toggleClass('clicked').siblings().removeClass('clicked'); });
#box { width: 100px; height: 100px; border: 1px solid #ccc; transition: width 1s; } #box.clicked { width: 200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="box" class="dos"></div> <div id="box" class="dos"></div>
You don't need to play with adding/removing classes. 您不需要玩添加/删除类。 Here is the new fiddle
这是新的小提琴
Edit your jQuery code with this, I have just added a boolean variable: 以此编辑您的jQuery代码,我刚刚添加了一个布尔变量:
var toggle = false;
$('.dos').click(function() {
toggle = !toggle;
if (toggle) {
$(this).toggleClass('clicked');
}
});
$('.dos').click(function() {
toggle = !toggle;
if (toggle) {
$('.dos').removeClass('clicked');
$(this).addClass('clicked');
}
});
You are removing the class from the clicked button as well, if you want to achieve it you'll need to ignore the one clicked while removing the class 您也要从单击按钮中删除该类,如果要实现它,则在删除该类时需要忽略单击的那个
$('.dos').click(function() {
$('.dos').not(this).removeClass('clicked');
$(this).toggleClass('clicked');
});
Solution is as below: 解决方法如下:
You was trying to toggle already toggled div. 您试图切换已切换的div。 Plus always use unique ids in your code :)
另外,请始终在代码中使用唯一的ID :)
$('.dos').click(function() {
var out = this;
$( ".dos" ).each(function( index ,element ) {
console.log(element);
if($(element).attr("id") != $(out).attr("id")){
$(this).removeClass('clicked');
}
});
$(this).toggleClass('clicked');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.