像列表上的按钮一样,按效果始终位于第一个 - javascript

我的问题是:

我无法显示已经选择的按钮(“向上投票”或“向下投票”)-视图代码中的变量。
当我按下最后评论的按钮时,例如“投票”。 -第一个评论上的“投票”按钮被突出显示-未进行排序。

问题可能是这是一个列表,另外是在视图中,其中对象已经是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()

这是详细视图,我想在其中查看是否喜欢评论。我传递给上下文变量。

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

以下是赞成或反对的网址和视图:

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>

然后处理正确的按钮,可能是使用data-*属性单击您的javascript。

当<form>'.submit'函数被覆盖时(使用Ajax)将数据获取到php吗? - javascript

我已覆盖此网页上表单的.submit函数,因为该网页已加载在“ index.php”中的#mainContent内,并且我希望“提交”按钮仅替换此#mainContent。我正在尝试将数据从此表单获取到.php文件,以便对数据库进行查询(或简单地回显已填充的变量,以指示已传递数据)。我是AJAX的新手。有人可以向我解释如何将数据传递到.php文件,或者指向要…

使用php重新加载内容 - javascript

在对网站进行编程时,我以前使用过此代码,它可以完美工作,但是现在当我想使用一些Flash部件时,每次单击链接时,它都会重新加载所有网站。源代码: <!DOCTYPE html> <html> <head> <title>Hot King Staff</title> <meta charset=…

用jQuery填充模式形式 - javascript

我正在将订单表从数据库绘制到datatables(jquery插件)中。我要在每笔最后一笔交易或每笔交易中增加付款。问题是,如何获取单击添加付款按钮以添加付款的行的订单ID。其次,当点击addpayment时,它会弹出一个带有字段或订单号的模态表单。我想用在td中找到的订单ID填充该字段,并使其不可编辑或隐藏,但在提交模态表单时将其发布到服务器。表格和模式表…

保留文本区域的数据或值,然后选择输入 - javascript

通过$ _POST提交表单时,输入文件值仍然保留。像这样: if($_POST){ $error = false; if(!$post['price']){ $error = true; $error_note['price'] = "*Should not be empty"; } if($err…

混合码错误 - javascript

好的,我在网站上为用户个人资料提供了一个基本的多合一页面,如下所示:<?php if($_GET['p']=='pb'){ echo '<p>pb</p>'; }elseif($_GET['p']=='example2'){ ec…