[英]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.我知道我不应该在循环中使用 forEach,但对 JS 来说还很新,我似乎找不到合适的解决方案。 Here is my code这是我的代码
main.js 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 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 %}
<div class="card" id = "{{d.id}}">
您需要唯一的 ID,例如<div class="card" id = "{{d.id}}">
$("[data-postid]").on("click",likeOnClick)
and和
function likeOnClick() { const id = this.dataset.postid;...
You need also to make data-postid
all lowercase您还需要将data-postid
全部设为小写
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.