遍历 DOM 元素导致所有相等的元素受到影响

Looping through a DOM element causing all equal elements to be affected

我有一个基本的 Javascript 本地实现的点赞按钮和一个每次单击该按钮时递增的数字。包含赞按钮和数字的部分由 EJS 呈现。

HTML

<section id="post-section">

   <%  posts.forEach(function(post) { %>

   <article class="post-container">
       <div class="post-title-container">
           <a href="/post/<%=post.title%>"><%=post.title%></a>
       </div>
       <div class="post-card-container">
           <img class="post-user-image" src="/img/user.png" alt="Imagem do utilizador">
           <p class="post-user-name"><%=post.name%></p>
           <% if (post.content.length > 100) { %>
           <span class="post-body"><%=post.content.substring(0, 100) + " ..."%></span>
           <% } else { %>
                   <span class="post-body"><%=post.content%></span>
           <% } %>
           <span class="post-date">
               <%=post.date%>
           </span>
           <span class="post-like">
               <i class="far fa-heart"></i>
           </span>
           <p class="post-like--count">
               0
           </p>
       </div>
   </article>
   <hr>
   
   <% }); %>
   
</section>

JavaScript

window.onload = function () {
    postLikeCount();
}

function postLikeCount() {
    let likeCount = document.querySelectorAll('.post-like--count');
    let postLikeButtons = document.querySelectorAll('.post-like .far.fa-heart');

    postLikeButtons.forEach(function (postLikeButton) {
        postLikeButton.addEventListener('click', function () {
            postLikeButton.classList.toggle('fas');
            
            likeCount.forEach(function (like) {

                let number = like.textContent;
                
                if (postLikeButton.classList.contains('fas')) {
                    number++;
                    like.textContent = number;
                }
                else {
                    number--;
                    like.textContent = number;
                }
            });
        });
    });
}

我的问题是,当触发 'click' 事件时数字会正确递增,但是,如果我有 multiple 个帖子(如 HTML 中所示),它也会增加这些按钮上的数字。

调试时,行为似乎是正确的。 likeCount returns 我是一个节点列表,其大小与该页面上的按钮数量有关,循环时,like 也给出抓取单个元素时的正确行为,但每个元素都会递增。

我认为您的代码中嵌套过多,并且您的选择器没有针对特定元素,而是所有具有相同 类.

的元素

你可以这样简化:

function postLikeCount() {
  document
    .querySelectorAll(".post-like .far.fa-heart")
    .forEach(function (postLikeButton) {
      postLikeButton.addEventListener('click', function () {
        // this is the clicked element
        this.classList.toggle("fas");
        // read its sibling count
        let number = this.parentNode.nextElementSibling.innerText;
        if (this.classList.contains("fas")) {
          number++;
          this.parentNode.nextElementSibling.innerText = number;
        } else {
          number--;
          this.parentNode.nextElementSibling.innerText = number;
        }
    });
  });
}