![](/img/trans.png)
[英]addClass “input-invalid” to input doesn't show until I click outside the input element
[英].addClass() to element nearby $(this) but outside of it
我有这个:
<div class="mycontainer active">
<a href="#" class="mylink">link</a>
</div>
<div class="mycontainer">
<a href="#" class="mylink">link</a>
</div>
当我单击其中的链接时,我想将活动类“移动”到第二个容器。
我尝试使用以下jQuery:
$('.mycontainer .mylink').on('click', function(){
$(".active").removeClass('active');
$(this).parent().find(".mycontainer").addClass('active');
});
但这是行不通的,实际上我对Javascript / jQuery不太了解,我在做什么错? 感谢您提供任何帮助。
您可以改用:
$('.mycontainer .mylink').on('click', function () {
$(this).closest('.mycontainer').addClass('active').siblings('.mycontainer.active').removeClass('active');
});
尝试:
$(this).parent().addClass('active');
要么:
$(this).parent(".mycontainer").addClass('active');
代替。 因为$(this).parent()
已经引用了您要查找的元素,然后使用find()
尝试在其中使用类mycontainer
元素将无法正常工作。
该行:
$(this).parent().find(".mycontainer")
正在找到mycontainer div,然后在实际上已经存在的情况下在其中查找.mycontainer。
尝试以下方法:
$('.mycontainer .mylink').on('click', function(){
$(".active").removeClass('active');
$(this).parent().addClass('active');
});
您要在正在单击的链接上添加活动类...
示例: http : //jsfiddle.net/LCaNP/
$('.mycontainer .mylink').on('click', function(){
$('.mycontainer').removeClass('active');
$(this).parent().addClass('active');
});
$('.myContainer').toggleClass('active')
应该这样做。
它将删除存在的类,并添加不存在的类。 签出.toggleclass()
因此,代码将是-
$('.mycontainer .mylink').on('click', function(){
$('.myContainer').toggleClass('active');
});
这是一个JSFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.