【发布时间】:2021-12-08 21:26:44
【问题描述】:
我需要知道如何解决以下问题。
我正在研究博客文章的喜欢/不喜欢系统,该系统仅在本地存储中记住用户喜欢的内容。
问题是,当我喜欢帖子时,按钮会被禁用(应该如此),但是当我重新加载页面时,喜欢的数量会增加(点赞按钮仍然被点击)。我该如何解决这个问题?
<!-- Likes button -->
<button id="likebtn" type="button">
<input type="number" id="input1" value ="<?php echo $post_likes;?>"</input>
</button>
</p>
<script>
let likebtn = document.querySelector('#likebtn');
let input = document.querySelector('#input1');
//local storage - saving ID of liked post
var likedID = parseInt('<?php echo $link_post_id ?>');
var likedIDhistory = JSON.parse(localStorage.getItem("arrayOfLikedPosts")) || [];
var isLiked = false;
for (var i = 0; i < likedIDhistory.length; i++){
var arrayLS = JSON.parse(localStorage["arrayOfLikedPosts"]);
var actual = arrayLS[i];
if(likedID == actual) {
isLiked= true;
console.log("true");
}
}
//if is not liked by "user"
if (isLiked == false) {
likebtn.addEventListener('click', likes_function=>
{
input1.value = <?php echo $post_likes?> + 1;
input.style.color = "#a1c4fd";
<?php
$like_query = "UPDATE posts SET post_likes_count=post_likes_count +1 WHERE post_id=$link_post_id";
$send_query2 = mysqli_query($connection, $like_query);
$query2 = "SELECT * FROM posts WHERE post_id=$link_post_id";
$like_post_query = mysqli_query($connection, $query2);
?>
likedIDhistory.push(likedID);
localStorage.setItem("arrayOfLikedPosts", JSON.stringify(likedIDhistory));
document.getElementById("likebtn").disabled = true;
document.getElementById("likebtn").style.opacity=0.5;
});
//if is already liked by "user"
} else {
document.getElementById("likebtn").disabled = true;
document.getElementById("likebtn").style.opacity=0.5;
}
</script>
【问题讨论】:
标签: javascript html jquery local-storage