多个fa-heart计数递增和递减

时间:2018-08-30 14:13:41

标签: javascript jquery html css onclick

我需要在点击时增加fa-heart值的计数,并在第二次点击时减少。

问题是我在同一页面上有多个fa-heart,因此无法在单击的fa-heart上增加/减少。

这是我下面的小提琴

https://jsfiddle.net/mehbub/d9e2qotg/1/

df.replace(r'[abc]+$', '', regex=True)
(function() {
  const heart = document.getElementById('heart');
  heart.addEventListener('click', function() {
    heart.classList.toggle('red');
  });
})();

$(document).on('click', ".notliked", function() {
    var $this = $(this);
    $this.removeClass('notliked');
    $this.addClass('liked')
    $count = $('.likes-count');
    $count.text(function(idx, txt) {
    return (+txt == 0) ? 0 : (+txt - 1);
    heart.classList.toggle('grey');

    });

});

$(document).on('click', ".liked", function() {
    var $this = $(this);
    $this.removeClass('liked');
    $this.addClass('notliked');
    $count = $('.likes-count');
    $count.text(function(idx, txt) {
            return +txt + 1;
    heart.classList.toggle('red');

    });

});
$count.text(function(idx, txt) {
   // convert text to number and increment by one
   return +txt + 1;
});
#heart {
  color: grey;  
  font-size: 20px;
}

#heart.red {
  color: red;
}

我需要为每个fa-heart单独单击增加/减少,以使颜色在增加时变为红色,在减少时变为灰色

谢谢

1 个答案:

答案 0 :(得分:1)

您应该删除重复的ID heart,或者由于已经有heart类而将其删除,然后将点击附加到该普通类并切换liked/notliked类,您可以使用这些类作为CSS中的规则,因此不需要red/grey类,例如:

$(document).on('click', ".heart", function() {
  var count = $(this).next('span');

  $(this).toggleClass('notliked liked');

  if ($(this).hasClass('liked')) {
    count.text(Number(count.text()) + 1);
  } else {
    count.text(Number(count.text()) - 1);
  }
});
.heart.notliked {
  color: grey;
  font-size: 20px;
}

.heart.liked {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<p>robert stephen</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 100 </span><br>

<p>James Camroon</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 101 </span><br>

<p>John Wick</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 37 </span><br>

<p>James Bond</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 22 </span><br>

<p>Avengers</p>
<i class="fa fa-heart liked heart" value="1"></i>
<span class="likes-count"> 90 </span>