jQuery - 添加活动类并在点击时从其他元素中移除活动 [英] jQuery - Add active class and remove active from other element on click
问题描述
我是jQuery的新手,所以如果这是一个愚蠢的问题,我很抱歉。但我一直在寻找Stack Overflow,我可以找到一半工作,我无法完全工作。
我有2个选项卡 - 1是积极的,另一个不是。一旦单击非活动选项卡,我想让它被赋予活动类别,并且要移除先前的活动类别。反过来,每次点击一个不活动的标签。
任何帮助都会很棒!
以下是我目前的服务:
http://jsfiddle.net/zLpe5/
以下是我尝试添加和移除类的原因:
$(document).ready(function(){
$(。tab)。click(function(){
$(.tab)。removeClass(active);
$(。tab).addClass(active);
});
}) ;
如果有人可以帮忙合并我的小提琴中的2位剧本,也帮助。
谢谢:)
$(document).ready(function(){
$(。 ())。click(function(){
$(。tab)。removeClass(active);
// $(。tab)。addClass(active); //而不是这样做
$(this).addClass(active);
});
});
当您使用 $(。tab)。addClass(活动);
,它定位所有类名为 .tab
的元素。相反,当您使用这个
时,它会查找包含事件的元素,在您的情况下,点击的元素。 />
希望这可以帮助你。
I'm new to jQuery, so I'm sorry if this is a silly question. But I've been looking through Stack Overflow and I can find things that half work, I just can't get it to fully work.
I have 2 tabs - 1 is active, the other is not. Once the inactive tab is clicked, I want that to be given the class of active, and the previous active class to be removed. And vice versa each time an inactive tab is clicked.
Any help would be great!
Here's what I currently have: http://jsfiddle.net/zLpe5/
Here's what I've tried for adding and removing the class:
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
$(".tab").addClass("active");
});
});
If anybody could help with with merging the 2 bits of script in my fiddle that'd be a massive help too. As I'm quite confused about how that's done!
Thank you :)
Try this
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
// $(".tab").addClass("active"); // instead of this do the below
$(this).addClass("active");
});
});
when you are using $(".tab").addClass("active");
, it targets all the elements with class name .tab
. Instead when you use this
it looks for the element which has an event, in your case the element which is clicked.
Hope this helps you.
这篇关于jQuery - 添加活动类并在点击时从其他元素中移除活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!