简体   繁体   中英

Javascript Else Statement Being Executed Despite If Statement Being True

I am attempting to implement a 3-state html label with javascript that iterates between 3 different css class names when the user click on the label. I've used a simple if -> else if -> else if statement to toggle between the 3 class states, but for some reason, it is always executing both the first true if statement and then the next else statement even though it already hit a true if statement first.

I'm a bit perplexed how this is happening as else statements are supposed to be skipped after a true if statement is hit.

Here's my code:

$(".goal-label").on('click', function() {
      if ($(this).hasClass('active_goal')) {
        alert('has active_goal');
        $(this).removeClass('active_goal');
        return $(this).addClass('complete_goal');
      } else if ($(this).hasClass('complete_goal')) {
        alert('has complete_goal');
        $(this).removeClass('complete_goal');
        return $(this).addClass('failed_goal');
      } else if ($(this).hasClass('failed_goal')) {
        $(this).removeClass('failed_goal');
        return $(this).addClass('active_goal');
      }
    });

So the initial class on the label is "active_goal" and when I click on it I see the alert "has active_goal" and I then I immediately see another alert "has complete_goal" which is inside the else if statement after the if statement that is being triggered by the label having the class "active_goal".

What am I doing wrong here? Thanks so much for any help.

I still don't know what was causing my click events to trigger twice but I discovered that adding a return false at the end of the click function stopped it from happening the second time so everything seems to be working now.

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