javascript - 用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
?
解决方案
document.querySelectorAll(".like-btn").forEach(el => el.addEventListener("click", () => {
count++
el.innerText = count
console.log(el)
}))
您不能将事件侦听器添加到 NodeList,您需要针对单个元素。
推荐阅读
- javascript - Angular 和 RxJs:处理验证码过期
- algorithm - 如何在数组中找到相同元素的子序列
- google-apps-script - 可安装的触发器只是不断被禁用
- php - 如何在php中验证广告组成员身份
- php - Laravel/PHP:我的 unix 时间戳没有显示为小于我的系统时间
- r - 将列数据框拆分为多列
- c# - oAuth 2.0 和 TD Ameritrade 的不记名令牌
- java - 我无法读取总行数,有些行被混淆了
- python - 将参数化夹具与 pytest 中的参数化测试相关联
- reactjs - (React) 使用 Framer-Motion 页面转换的延迟加载组件