addClass and removeClass in jQuery - not removing class

后端 未结 10 1577
不知归路
不知归路 2020-12-05 02:02

I\'m trying to do something very simple. Basically I have a clickable div \'hot spot\', when you click that it fills the screen and displays some content. I achieved this by

相关标签:
10条回答
  • 2020-12-05 02:57

    I think you're almost there. The thing is, your $(this) in the "close button" listener is not the clickable div. So you want to search it first. try to replace $(this) with $(this).closest(".clickable") . And don't forget the e.stopPropagation() as Guilherme is suggesting. that should be something like:

    $( document ).ready(function() {   
        $(document).on("click", ".close_button", function () { 
            alert ("oi");
            e.stopPropagation()
            $(this).closest(".clickable").addClass("spot");
            $(this).closest(".clickable").removeClass("grown");
        });  
    
    
        $(document).on("click", ".clickable", function () {
            if ($(this).hasClass("spot")){
                $(this).addClass("grown");
                $(this).removeClass("spot");
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-05 02:58

    Use .on()

    you need event delegation as these classes are not present on DOM when DOM is ready.

    $(document).on("click", ".clickable", function () {
        $(this).addClass("grown");
        $(this).removeClass("spot");
    });
    $(document).on("click", ".close_button", function () {  
        $("#spot1").removeClass("grown");
        $("#spot1").addClass("spot");
    });  
    
    0 讨论(0)
  • 2020-12-05 03:04

    The issue is caused because of event bubbling. The first part of your code to add .grown works fine.

    The second part "removing grown class" on clicking the link doesn't work as expected as both the handler for .close_button and .clickable are executed. So it removes and readd the grown class to the div.

    You can avoid this by using e.stopPropagation() inside .close_button click handler to avoid the event from bubbling.

    DEMO: http://jsfiddle.net/vL8DP/

    Full Code

    $(document).on('click', '.clickable', function () {
       $(this).addClass('grown').removeClass('spot');
    }).on('click', '.close_button', function (e) {
       e.stopPropagation();
       $(this).closest('.clickable').removeClass('grown').addClass('spot');
    });
    
    0 讨论(0)
  • 2020-12-05 03:08

    I actually just resolved an issue I was having by swapping around the order that I was altering the properties in. For example I was changing the attribute first but I actually had to remove the class and add the new class before modifying the attributes. I'm not sure why it worked but it did. So something to try would be to change from $("XXXX").attr('something').removeClass( "class" ).addClass( "newClass" ) to $("XXXX").removeClass( "class" ).addClass( "newClass" ).attr('something').

    0 讨论(0)
提交回复
热议问题