简体   繁体   中英

I am creating a like and dislike button, but it toggles the like count for ALL posts on the page, instead of the post being liked

I've attached a screenshot of my project to better explain my dilemma. When I click on the first thumbs up button, it updates the count for ALL posts on the page when it should update the count for that post only. I know I shouldn't be using forEach in a loop but being fairly new to JS, I can't seem to find a proper solution. Here is my code

main.js

function likeOnClick(ele, id) {
    var postId;
    postId = id;
    console.log("I went inside the function", postId);
  
    
    var currentClass = $(ele).attr('class');
    if (currentClass == 'fa fa-thumbs-up')
    {
        console.log("dislike");
     $(ele).removeClass("fa fa-thumbs-up");   
        $(ele).addClass("fa fa-thumbs-down");
    }
    else{
        console.log("Like button");
        $(ele).removeClass("fa fa-thumbs-down");   
        $(ele).addClass("fa fa-thumbs-up");
    }   

    fetch(`/like_post/${id}`)
    .then(response=> response.json())
    .then(updateCount => {
        updateCount.forEach(element => {
            $('#cardID strong').text(`${element.likes}`);
            console.log("likes in JS are", `${element.likes}`);
            return

        })
    });
   };

HTML

{% for d in page_obj %}
<div class="secondSection">
    <div class="container">
        <div class="card" id = "cardID">
            <h4><a href="profile/{{d.created_by}}" class="userNameClick">{{d.created_by}}</a></h4>
            
            {% if request.user == d.created_by %}
            <a href="#" onclick="loadModal('{{d.id}}');" id="editLink">Edit</a>
            {% endif %}

            <p id="contents">{{d.postContent}}</p>
            <small>{{d.dateAndTime}}</small>

            <strong id = "like_count">{{ d.likes }}</strong>
            {% if user.is_authenticated %}
            <i class="fa fa-thumbs-up" id="likes" data-postId="{{d.id}}" onclick="likeOnClick(this, '{{d.id}}');"></i>
            {% endif %}

        </div>
    </div>
    {% endfor %}

  1. You need unique IDs for example <div class="card" id = "{{d.id}}">
  2. Then you can do
$("[data-postid]").on("click",likeOnClick) 

and

function likeOnClick() { const id = this.dataset.postid;...

You need also to make data-postid all lowercase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM