【问题标题】:Django load more comments with AJAX [duplicate]Django使用AJAX加载更多评论[重复]
【发布时间】:2020-01-20 03:33:57
【问题描述】:

在个人资料页面中,我想显示用户的帖子。每个帖子可能有几个 cmets,我不想在帖子中显示所有 cmets,而是只想显示几个 cmets 并添加加载更多 cmets 选项。如果用户单击加载更多 cmets,那么我想显示更多 cmets。有什么更好的方法来做到这一点?我已经在使用无限滚动的帖子分页。我认为这可能不适用于 cmets。

我的当前代码如下所示

{% for post in post_queryset %}
   <div class="title">
     {{ post.title }}
   </div>
   {% for comment in post.comments.all %}
   </div>
     {{ comment.text }}
   </div>
   {% endfor %}
{% endfor %}

上面的代码简化了原始版本,使事情变得更容易。

【问题讨论】:

标签: django django-pagination django-comments


【解决方案1】:

对于动态页面内容,最好的方法是使用 jquery 和 bootstrap。

在渲染模板时,您可以在第 10 个或后面的元素中添加类“d-none”(隐藏元素的内容):

{% for post in post_queryset %}
   <div name="comment-block">
       <div class="title">
         {{ post.title }}
       </div>
       {% for comment in post.comments.all %}
       <div {% if forloop.counter > 9 %} class="d-none" {% endif %} >
       {{ comment.text }}
       </div>
       {% endfor %}
       <button type="button" name="more_comments" class="btn btn-primary" > more comments </button>
   </div>
{% endfor %}

这样,所有的 cmets 都会被渲染,但只有前 10 个会显示。

之后,由按钮单击触发的 jquery 函数应该可以解决问题

$("[name='more_comments']".click(function(){
    var hidden_comments = $(this).parent().find('.d-none'); // selects all hidden comments
    $(hidden_comments).each(function(){$(this).removeClass('d-none')}); // removes 'd-none' class
    })

请记住,您的原始代码(无论是我的回答)都不符合 bootstrap,强烈建议您这样做。您可以在https://getbootstrap.com/ 中了解有关引导程序的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2020-12-18
    • 2011-09-03
    相关资源
    最近更新 更多