jQuery:检查当前切换的类

时间:2018-11-27 22:54:27

标签: javascript jquery web

所以,这是我的代码

     $(".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>

要检查此函数的当前位置是fa-heart-o还是fa-heart

3 个答案:

答案 0 :(得分:2)

hasClass函数可能就是您想要的https://api.jquery.com/hasclass/

因此,您将执行以下操作:

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

答案 1 :(得分:1)

试试这个-

$(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');
}

答案 2 :(得分:1)

具有三元运算符和更重要变化的更短语法:

$(".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");
});

我正在使用e.target而不是this。安全胜过遗憾。您可以了解差异here