最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Add Class on Click but only allowed once. - Stack Overflow

programmeradmin1浏览0评论

Here is what I have so far:

Javascript:

$(document).ready(function() {
    $(".thumb_wrapper").click(function() {
        $(this).addClass("active");
    });
});

So this is working, it is adding the class but I want only one item to be active at all times. So when I click on an item, and it turns active, the next item I click on should be the new active one, and remove the class on the previous one.

Does that make sense? How can I do something like this?

Thanks!

Here is what I have so far:

Javascript:

$(document).ready(function() {
    $(".thumb_wrapper").click(function() {
        $(this).addClass("active");
    });
});

So this is working, it is adding the class but I want only one item to be active at all times. So when I click on an item, and it turns active, the next item I click on should be the new active one, and remove the class on the previous one.

Does that make sense? How can I do something like this?

Thanks!

Share Improve this question asked Apr 9, 2012 at 15:37 DrewDrew 6,86219 gold badges65 silver badges97 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 13

You need to first remove the active class from your thumb_wrapper elements. Try this:

$(".thumb_wrapper").click(function() {
    $(".thumb_wrapper").removeClass("active");
    $(this).addClass("active");
});

Cache your wrapper and call a removeClass() on it first:

var $wrapper = $(".thumb_wrapper");

$wrapper.click(function() {
    $wrapper.removeClass("active");
    $(this).addClass("active");
});
$(".thumb_wrapper").on('click', function() {
    $(".thumb_wrapper").removeClass('active').find(this).addClass("active");
});

This should do it.

$(document).ready(function() {
    $(".thumb_wrapper").click(function() {
        $(this).parent().children().each(function() { 
             $(this).removeClass("active");
         });
         $(this).addClass("active");
     });
});
$(document).ready(function(){
    $('.what').click(function(){
        $('.what').removeClass('active');
        $(this).addClass('active');       
   });       
});

I assume something like this?

发布评论

评论列表(0)

  1. 暂无评论