简体   繁体   中英

jquery: check the current toggled class

So, this is my code

     $(".heart.fa").click(function() {
          $(this).toggleClass("fa-heart fa-heart-o");

//Wanna check here is its fa-heart or fa-heart-o

           var row = $(this).closest("i");
           var rowId = row.attr("id");
            alert(rowId);

        });

<div>
  <i id= '".$i."' class='heart fa fa-heart-o'></i>
</div>

Want to check inside this function if it's currently fa-heart-o or fa-heart

The hasClass function is probably what you want https://api.jquery.com/hasclass/

So you would do something like:

if($(this).hasClass('fa-heart-o')){
//logic for having fa-heart-o
}
else{
//logic for having fa-heart
}

Try this-

$(this).toggleClass("fa-heart fa-heart-o");

if($(this).hasClass('fa-heart') && !$(this).hasClass('fa-heart-o')){
  console.log('class is fa-heart');
} else if($(this).hasClass('fa-heart-o') && !$(this).hasClass('fa-heart')){
  console.log('class is fa-heart-o');
}

Shorter syntax with ternary operator and one major change:

$(".heart.fa").click(function(e) {
    $(e.target).toggleClass("fa-heart fa-heart-o");

    $(e.target).hasClass("fa-heart-o") ? console.log("It was fa-heart-o") : console.log("It was fa-heart");
});

I am using e.target instead of this . Better safe than sorry. You can read about the differences here .

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