addClass and removeClass in jQuery - not removing class

后端 未结 10 1602
不知归路
不知归路 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 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');
    });
    

提交回复
热议问题