首页 > 解决方案 > 单击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)
  }))
}

例子

标签: javascript

解决方案


而不是使用 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
            }
        });
    });
}

推荐阅读