jQuery -添加活动类并在单击时从其他元素中删除活动类
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.
我是jQuery新手,如果这是一个愚蠢的问题,我很抱歉。但是我已经检查了堆栈溢出,我可以找到那些工作了一半的东西,我就是不能让它完全工作。
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.
我有两个标签- 1是活动的,另一个不是。单击inactive选项卡之后,我希望它被授予active类,并删除之前的active类。反之亦然,每次单击不活动的选项卡时。
Any help would be great!
任何帮助都将是伟大的!
Here's what I currently have: http://jsfiddle.net/zLpe5/
下面是我目前拥有的: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 :)
谢谢你:)
6 个解决方案
#1
29
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.
当您使用$(“.tab”). addclass(“active”)时,它会以类名.tab为目标来处理所有的元素。相反,当您使用它时,它会查找具有事件的元素,在您的示例中是单击的元素。希望这能帮助你。
更多相关文章
- 仅当鼠标停留在元素上时,jQuery才会激活鼠标悬停函数
- 动态添加表单元素,将它们存储到MySQL并在将来更改/删除它们
- 3.29 学前端 jquery之操作元素之属性操作
- 禁用焦点上的锚点()元素上的灰色边框
- 在jQuery中使用部分ID查找元素?(复制)
- 使用数字作为javascript对象元素的名称
- 确定焦点事件:单击或tabstop
- 单击文件输入后,Fancybox正在关闭
- 使用类似$(“。someClass”)的JQuery确定元素集合是否可见