简体   繁体   中英

jQuery Add Class on Click but only allowed once.

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!

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM