首页 > 解决方案 > 用javascript点击计数器

问题描述

这是我试图创建一个类似的计数器并在图像上方显示点击次数。但是,如果我只针对类而不循环它,我似乎可以让它工作。但我需要循环,因为我在其他项目上获得了相同的课程。.querySelectorAll在控制台内返回正确的点击次数,但即使我指定了也不显示它.innerHTML

// heart animation when we click on it    
$('.like-btn').on('click', function() {
  $(this).toggleClass('is-active');
});

//click counter
var like_button = document.querySelectorAll('.like-btn'),
count = 0;  
for (var i = 0; i < like_button.length; i++) {
   like_button.onclick = function(){
  count += 1;
  like_button.innerHTML = "" + count;
  console.log(like_button)
    }
};
.like-btn {
  position: absolute;
  top: 10px;
  display: block;
  width: 60px;
  height: 60px;
  -webkit-box-pack: end;
  -webkit-justify-content: flex-end;
  -ms-flex-pack: end;
  justify-content: flex-end;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-align-self: flex-end;
  -ms-flex-item-align: end;
  align-self: flex-end;
  background: url('twitter-heart.png');
  Cursor: pointer;
  background-size: 2900%;
  background-repeat: no-repeat;
  z-index: 5;
}

.is-active {
  animation-name: animate;
  animation-duration: .8s;
  animation-iteration-count: 1;
  animation-timing-function: steps(28);
  animation-fill-mode: forwards;
}

@keyframes animate {
  0% {
    background-position: left;
  }
  50% {
    background-position: right;
  }
  100% {
    background-position: right;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="like-btn"></div>

我怀疑这nodelist会阻止它正常工作,我应该使用.foreach

标签: javascript

解决方案


document.querySelectorAll(".like-btn").forEach(el => el.addEventListener("click", () => {
    count++
    el.innerText = count
    console.log(el)
}))

您不能将事件侦听器添加到 NodeList,您需要针对单个元素。


推荐阅读