![](/img/trans.png)
[英]I am trying to create a like and dislike button for different posts on a page using JavaScript and Django but it seems to work first post only
[英]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
我附上了我的項目的截圖,以更好地解釋我的困境。 當我單擊第一個豎起大拇指按鈕時,它會更新頁面上所有帖子的計數,而它應該只更新該帖子的計數。 我知道我不應該在循環中使用 forEach,但對 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
{% 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}}">
$("[data-postid]").on("click",likeOnClick)
和
function likeOnClick() { const id = this.dataset.postid;...
您還需要將data-postid
全部設為小寫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.