javascript - 单击Javascript后如何停用按钮
问题描述
如果照片被喜欢(点击)一次,我想停止增加个人喜欢的数量,并增加每张喜欢(点击)的个人照片的喜欢总数
个人照片点赞likesAfterAddition
全球照片点赞globalNumberOfLikes
目前,每次点击个人和全球喜欢时它都会增加,我知道这不是正确的逻辑!
请问我可以使用什么逻辑?
//increment likes on click
function incrementLikesOnClick() {
const heartIcons = Array.from(document.getElementsByClassName('heartIcon')); // multiple heart icons
heartIcons.forEach((likeIcon, index) => likeIcon.addEventListener('click', () => {
const individualLikeBox = document.getElementsByClassName('under-photo-info');
const totalLikesDivBox = document.getElementById("likesBox");
likeIcon.classList.add('activeRed');
let likesAfterAddition = likesTable[index] + 1; // add 1 like to the individual current photo
likesTable.splice(index, 1, likesAfterAddition); // replace the old value from the Array with the new value
let sum = likesTable.reduce(function(a, b){return a + b;}); // return the sum of the array
let globalNumberOfLikes = sum; // the sum of the array
individualLikeBox[index].innerHTML = `<span'>${likesAfterAddition}</span>`
totalLikesDivBox.innerHTML = `<div class="Likes">${globalNumberOfLikes}<i class="fas fa-heart"></i></div>`
console.log(likesTable)
}))
}
解决方案
而不是使用 for 循环来设置效率不高的事件监听器
可以使用冒泡的特性,所以当点击任意一个dom元素时,事件会依次冒泡其父元素,直到到达父dom
//increment likes on click
function incrementLikesOnClick() {
document.addEventListener("DOMContentLoaded", function(event) {
// Your code to run since DOM is loaded and ready
document.addEventListener('click', () => {
let clicked = event.target;
//element with class heartIcon is clicked and it doesnt have activeRed class
if(clicked.classList.contains('heartIcon') && !clicked.classList.contains('activeRed')){
let productContainer = clicked.parentElement.parentElement; // till you reach the product container
const individualLikeBox = productContainer.getElementsByClassName('under-photo-info');
const totalLikesDivBox = productContainer.getElementById("likesBox");
clicked.classList.add('activeRed');
// ..whatever extra logic you want to add
}
});
});
}
推荐阅读
- javascript - 如何在量角器中恢复覆盖 browser.waitforAngular
- javascript - 在 while 循环中的 continue 语句之前使用增量运算符有什么区别?(JavaScript)
- sapui5 - sap.m.MultiComboBox:如何从所有选定项目中获取文本?
- typescript - 为什么 vscode 源代码包含手动编写的 vscode.d.ts 文件?
- angular - 如何实现事件发射器而不是刷新页面?
- amazon-web-services - 通过主机名使用 ALB 路由时运行状况检查失败
- json - 使用 JSON Merge Patch,我如何引用子集合的成员?
- r - R 从列中删除罗马数字
- angular - 如何通过按钮使用角度材料选择(无表单域)
- php - 一些 HTTP 响应的第一行变成了“未定义未定义未定义”