点击时如何保持按钮的颜色并刷新页面

我喜欢按钮的默认颜色是灰色,当用户点击按钮时,它会运行togglepost“like”,颜色将变为红色..如果用户点击按钮,我会使用ajax插入数据……如果用户再次点击“喜欢”按钮时它会显示“不喜欢”,并且我的数据库中的数据将被删除。

按钮就像


   Love

jquery函数

  $(".like").click(function(){ $('.boxcoracao .coracao',this).toggleClass("ativo"); var lpid = $(this).closest("div#buttons").find("#likepid").val(); var lmid = $(this).closest("div#buttons").find("#likemid").val(); if ($('.boxcoracao .coracao',this).hasClass("ativo")){ // update the text to show what the next click would be togglePost("like", lpid, lmid); // run function alert("succes"); } else { // update the text to show what the next click would be togglePost("dislike", lpid, lmid); // run function alert("failed"); } function togglePost(action,lpid,lmid){ $.ajax({ type: "post", url: "../controller/like_controller.php", data: "action="+action+"&postid="+lpid+"&postmember="+lmid, success: function(data){ window.location.reload(); }, error: function(e){ alert("please try again..."); } }); } });  

这是我的SQL查询 ….

  function UpdateLikes($postid, $postmember, $likeid, $action){ if ($action == "dislike"){ $sql = "DELETE FROM plike WHERE pl_puid = '$postid' AND pl_uid = '$likeid'"; var_dump($sql); $result = $this->dbh->prepare($sql); $result->execute(); return $result->rowCount() ? true : false; } else{ // before inserting you might want to check if they alredy liked or not before adding their count again. $query = "INSERT INTO plike SET pl_puid='$postid',pl_memid='$postmember',pl_uid='$likeid'"; $query = $this->dbh->prepare($query); var_dump($query); $result = ($query->execute() ? true : false); return $result; } } 

这是gif按钮..

在此处输入图像描述

但我的问题是当用户点击类似按钮并刷新页面时,类似按钮将重置为灰色而不是红色..如何解决这个问题的任何想法?当用户点击时它会变红并且当用户刷新时页面按钮仍然是红色,除非用户再次按下按钮不同?

例如,您必须执行一些Ajax来保存数据库中的状态或文件系统上的某些缓存。

如果您想要不那么健壮的东西,可以将状态保存在cookie或localstorage中。 或者甚至更少持久性:在会话变量中,一旦浏览器会话丢失就会消失。

然后,当请求页面时,检查数据库,缓存,cookie,会话或其他内容中是​​否存在您的状态,并在HTML中为该按钮指定相应的类。

例如,如果您使用的是PHP,则可以这样做:

  

   Love