Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - jQuery - Add active class and remove active from other element on click

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...