简体   繁体   中英

Javascript addClass removeClass not working as desired

When I click on the icon, I want it to be switched on/off.

In my html file I have:

<div class="startSharing"></div>

And in my js:

$('.startSharing').click(function() {
    $(this).removeClass('startSharing');
    $(this).addClass('stopSharing');
});

$('.stopSharing').click(function() {
    $(this).removeClass('stopSharing');
    $(this).addClass('startSharing');
});

It works fine when switching from on to off - but I don't understand why it still goes into "startSharing" section when it is turned off.

Thank you for help.

In this case, you're setting the handlers to the particular elements. Once they're set - they're set, regardless of the selector changing.

You could just define it on the .startSharing element, if they all start like that. Then, you could use .toggleClass() to easily switch them on/off:

$('.startSharing').click(function() {
    $(this).toggleClass('startSharing stopSharing');
});

You may also delegate the click event like this:

$('body').on('click', '.startSharing', function() {
  $(this).removeClass('startSharing').addClass('stopSharing');
});

$('body').on('click', '.stopSharing', function() {
  $(this).removeClass('stopSharing').addClass('startSharing');
});

Doing it this way will also allow dynamically-generated to trigger events. In your case, .stopSharing was generated dynamically.

use event delegation

 $('#container').on('click',".startSharing,.stopSharing",function(){ $(this).toggleClass('startSharing').toggleClass('stopSharing'); }); 
 #container div { width: 250px; height: 100px; } .startSharing { background-color: green; } .startSharing::after { content: "start sharing"; } .stopSharing { background-color: red; } .stopSharing::after { content: "stop sharing"; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div class="startSharing"></div> </div> 

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