javascript - 列表中的喜欢按钮,按下效果始终位于第一个

标签 javascript python jquery ajax django

我的问题是:

  1. 我无法显示已选择的按钮(“投票赞成”或“投票反对”) - View 代码中的变量。
  2. 当我按下最后一条评论上的按钮时,例如“投票”。 - 第一条评论上的“投票”按钮突出显示 - 尚未整理。

问题可能是这是一个列表,而且是在 View 中,其中对象已经是 Post 模型。

我的代码如下。

这是帖子和评论的模型

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = RichTextUploadingField()
    votes_up = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='up_votes')
    votes_down = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='down_votes')

    def __str__(self):
        return self.text

    def total_vote_up(self):
        return self.votes_up.count()

    def total_vote_down(self):
        return self.votes_down.count()


class Comment(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    text = RichTextUploadingField()

这是详细 View ,我想检查评论是否被喜欢。我传递给上下文变量。

class PostDetail(generic.DetailView, FormMixin):
    template_name = 'post_detail.html'
    context_object_name = 'post'
    model = Post
    form_class = CommentForm

    def get_context_data(self, **kwargs):
        is_voted_up = False
        is_voted_down = False

        comments = self.get_object().comments.all()
        for comment in comments:
            if answer.votes_up.filter(id=self.request.user.id).exists():
                print(answer)
                is_voted_up = True
                print(is_voted_up)
            if answer.votes_down.filter(id=self.request.user.id).exists():
                is_voted_down = True

        context = super(PostDetail, self).get_context_data(**kwargs)
        context['comments'] = comments
        context['form'] = CommentForm(initial={'post': self.get_object(), 'author': self.get_user()})
        context['is_voted_up'] = is_voted_up
        context['is_voted_down'] = is_voted_down
        return context

以下是投票赞成或反对的网址和 View :

url(r'^voteup/$', login_required(CommentVoteUpView.as_view()), name='comment_voteup'),
url(r'^votedown/$', login_required(CommentVoteDownView.as_view()), name='comment_votedown'),


class CommentVoteUpView(generic.View):
    def post(self, request):
        comment = get_object_or_404(Comment, id=request.POST.get('id'))
        is_voted_up = False
        if comment.votes_up.filter(id=request.user.id).exists():
            comment.votes_up.remove(request.user)
            is_voted_up = False
        else:
            comment.votes_up.add(request.user)
            is_voted_up = True
        context = {
            'comment': comment,
            'is_voted_up': is_voted_up,
            'total_vote_up': comment.total_vote_up(),
            }
        if request.is_ajax():
            html = render_to_string('voteup_section.html', context, request=request)
            return JsonResponse({'form': html})


class CommentVoteDownView(generic.View):
    def post(self, request):
        comment = get_object_or_404(Comment, id=request.POST.get('id'))
        is_voted_down = False
        if comment.votes_down.filter(id=request.user.id).exists():
            comment.votes_down.remove(request.user)
            is_voted_down = False
        else:
            comment.votes_down.add(request.user)
            is_voted_down = True
        context = {
            'comment': comment,
            'is_voted_down': is_voted_down,
            'total_vote_down': comment.total_vote_down(),
            }
        if request.is_ajax():
            html = render_to_string('votedown_section.html', context, request=request)
            return JsonResponse({'form': html})

下面是jquery代码:

        <script type="text/javascript">
            $(document).ready(function(event){
                $(document).on('click', '#voteup', function(event){
                    event.preventDefault();
                    var pk = $(this).attr('value');
                    $.ajax({
                        type: 'POST',
                        url: "{% url 'comment_voteup' %}",
                        data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: 'json',
                        success: function(response){
                            $('#voteup-section').html(response['form'])
                            console.log($('#voteup-section').html(response['form']))
                        },
                        error: function(rs, e){
                            console.log(rs.responseText);
                        },
                    });
                });
            });
        </script>

        <script type="text/javascript">
            $(document).ready(function(event){
                $(document).on('click', '#votedown', function(event){
                    event.preventDefault();
                    var pk = $(this).attr('value');
                    $.ajax({
                        type: 'POST',
                        url: "{% url 'comment_votedown' %}",
                        data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
                        dataType: 'json',
                        success: function(response){
                            $('#votedown-section').html(response['form'])
                            console.log($('#votedown-section').html(response['form']))
                        },
                        error: function(rs, e){
                            console.log(rs.responseText);
                        },
                    });
                });
            });
        </script>

最后但并非最不重要的 html 部分 - 仅评论部分和投票部分的按钮:

          {% if comment %}
              <h5>{{ comment.count }} Answers:</h5>
              <hr>
              {% for comment in comments %}
              <div class="media mb-4">
                <img class="d-flex mr-3 rounded-circle" src="http://placehold.it/50x50" alt="">
                <div class="media-body">
                    <h5 class="mt-0">{{ comment.author }}</h5>
                    <p>{{ comment.text|safe }}</p>
                    <div class="btn-group btn-group-sm">
                        <div id="voteup-section">
                            {% include 'voteup_section.html' %}
                        </div>
                        <div id="votedown-section">
                            {% include 'votedown_section.html' %}
                        </div>
                    </div>
                </div>
              </div>
              {% if not forloop.last %}
              <hr>
              {% endif %}
              {% endfor %}
          {% endif %}

投票按钮:

<form action="{% url 'comment_voteup' %}" method="post">
    {% csrf_token %}
    <button type="submit" id="voteup" name="comment_id" value="{{ comment.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ total_vote_up }}</span></button>
</form>

我希望您能够对“投票赞成”或“投票反对”的每条评论进行投票,并了解选择了哪个按钮或“投票赞成”或“投票反对”。

最佳答案

如果 DOM 有多个具有相同 id 的元素,则任何代码如下:

$(#some_repeated_id)

将使用id=some_repeated_id引用第一个元素。话虽如此,我会建议一些更改:

<!-- div id="voteup-section" -->
<div id="voteup-section-{{ comment.id }}">

并以形式

<!--button type="submit" id="voteup-{{ comment.id }}" name="comment_id" value="{{ comment.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ total_vote_up }}</span></button-->

<button type="submit" id="voteup-{{ comment.id }}" name="comment_id" value="{{ comment.id }}" {% if is_voted_up %} class="btn btn-danger btn-sm">Voted up! {% else %} class="btn btn-primary btn-sm">Vote up!{% endif %} <span class="badge badge-light">{{ total_vote_up }}</span></button>

然后处理在 JavaScript 中单击的正确按钮,可能使用 data-* 属性。

关于javascript - 列表中的喜欢按钮,按下效果始终位于第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54354745/

相关文章:

javascript - 有没有办法设置javascript鼠标事件顺序?

javascript - 什么是 DOM 事件委托(delegate)?

python - 重新格式化 pandas 中的日期时间列

javascript - 我可以遍历 for 循环来创建更多的 javascript 吗?

javascript - 如何在 React Native 上访问数组状态或 json 数据?

javascript - 鼠标输入/鼠标输出事件

python - 如何使用numpy掩码计算二维数组

python - 以预编译的字节码 + 所有必需的库分发 python 脚本

javascript - 数组中的对象 : Unexpected String

javascript - 使用适用于移动设备的 javascript 将摄像头流式传输到服务器