如何停止网页滚动到顶部时,点击一个喜欢的按钮,node js,mongoose,JavaScript

cbjzeqam  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(136)

每次点击喜欢按钮时,网页都会滚动到顶部。有什么办法阻止这一切发生。密码是

<a href="/likeComment/{{../post._id}}/{{_id}}"> 
          <i class="fa-solid fa-thumbs-up"></i>
          {{likes.length}} Like
        </a>

喜欢被登记并且喜欢的数量被递增。然而,每次点击它都会跳到网页的顶部。我希望网页留在原地,当喜欢被点击。

c86crjj0

c86crjj01#

这是带有href的锚<a>元素的默认行为。当你点击它可以导致页面跳转到顶部。
更改为:<button><div>应该可以解决这个问题。

monwx1rj

monwx1rj2#

我通过在元素中添加onclick来解决这个问题

<a href="/likeComment/{{../post._id}}/{{_id}}" id="test" onclick="updateLikes(event, '{{../post._id}}', '{{_id}}')"> 
      <i class="fa-solid fa-thumbs-up"></i>
      {{likes.length}} Like
    </a>

然后使用AJAX来更新Like计数。

// Prevent the default link behavior
  event.preventDefault();

  const url = `/likeComment/${postId}/${commentId}`;

  var xhr = new XMLHttpRequest();

 
  xhr.open('GET', url, true);

  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      // The like count was successfully updated on the server
      // Now, reload the page to reflect the new like count
      location.reload();
    }
  };

  xhr.send();
}`

相关问题