简体   繁体   English

使用 jQuery 创建后反应

[英]Create post reaction using jQuery

I'm trying to generate a jQuery code with post review functionality.我正在尝试生成具有后审功能的 jQuery 代码。 What I want to create looks like the image below:我要创建的内容如下图所示:

在此处输入图像描述

Like and dislike buttons will be highlighted each time they are clicked.每次单击时,喜欢和不喜欢按钮都会突出显示。 The reaction will be stored locally using localStorage.反应将使用 localStorage 存储在本地。

This is my HTML code:这是我的 HTML 代码:

<div class="reaction-post" data-id="123456">
      <div class="like" data-title="like">Like</div>
      <div class="dislike" data-title="dislike">Dislike</div>
</div>

This is my jQuery code:这是我的 jQuery 代码:

$(function(){
    $('.reaction-post div').click(function(){
        var lod = $(this).attr('data-title');
        var idr = $('.reaction-post').attr('data-id');       
        localStorage.setItem(idr,lod);
        var ratinghis = localStorage.getItem(idr);
        $('.reaction-post').addClass(ratinghis);     
    });
});

My problem is I don't know how to removeClass after click to another option.我的问题是单击另一个选项后我不知道如何删除类。

Well you could add something like this at the start of the "click" handler:好吧,您可以在“click”处理程序的开头添加类似这样的内容:

$(".reaction-post").removeClass("dislike like"); $(".reaction-post").removeClass("不喜欢");

This will, on a like/dislike button click, remove all "like" or "dislike" class to your.reaction-post, and then your script applies a new one depending on the clicked button.这将在单击喜欢/不喜欢按钮时将所有“喜欢”或“不喜欢”class 删除到 your.reaction-post,然后您的脚本会根据单击的按钮应用一个新的。

Note: if you have many elements like this on your page (DOM) (many like and dislike button), you may want to restrict the class manipulation to the clicked element.注意:如果您的页面 (DOM) 上有很多这样的元素(很多喜欢和不喜欢按钮),您可能希望将 class 操作限制为单击的元素。

Edit: your code could look like this (not tested, but you get the idea):编辑:您的代码可能如下所示(未经测试,但您明白了):

<script>
$(function(){
    $('.reaction-post div').click(function(){
        var likable_element = $(this).parent(); //the .reaction-post, easier to manager multiple likeable element on the same page
        likable_element.removeClass("dislike like");
        
        var lod = $(this).attr('data-title');
        var idr = likable_element.attr('data-id');       
        localStorage.setItem(idr,lod);
        var ratinghis = localStorage.getItem(idr);
        likable_element.addClass(ratinghis);     
    });
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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