【问题标题】:How can I affect individual entries in a django for loop?如何影响 django for 循环中的单个条目?
【发布时间】:2020-09-10 15:46:32
【问题描述】:

我在 Django 中创建了一个 for 循环,用于显示用户上传的文章。对于长文章,我会将文本截断为最大 150 个字符,但希望读者可以选择使用 jquery 函数扩展文本,方法是单击“阅读更多”。 这是我的模板:

{% for post in posts %}
    {% if post.content|length > 150 %}
        <p class="half-content">{{ post.content|truncatechars:150 }}<a href="javascript:void();" class="show-hide-btn">read more</a></p>
        <p class="full-content" style="display: none;">{{ post.content }}</p>
    {% else %}
        <p>{{ post.content }}</p>
    {% endif %}
{% endfor %}

这是我的 jquery 函数:

$(document).ready(function(){
    $(".show-hide-btn").click(function(){
        $(".half-content").hide();
    });
});
$(document).ready(function(){
    $(".show-hide-btn").click(function(){
        $(".full-content").show();
    });
});

它可以按照我的意愿工作,只是“阅读更多”链接正在扩展页面上的所有文章,而不仅仅是具有适当主键的文章。我知道我需要在我的代码中的某个地方包含 {{ post.id }},但到目前为止我尝试的一切都无效。

【问题讨论】:

  • 你可以使用 javascript 来做这个
  • 谢谢,我已经编辑了我的问题
  • 阅读选择器。您应该将您的操作限制为具有“完整内容”的父级的姐妹元素。或者你可以让自己轻松一点,给每个帖子一个 id 并引用它。您可以为此使用forloop.counter - 例如或仅使用{{post.id}}
  • 感谢您的回复。我的帖子都有一个ID。你能告诉我应该在我的代码中的什么位置包含 {{ post.id }} 吗?

标签: jquery django tags truncate


【解决方案1】:

试试这个,

{% for post in posts %}
    {% if post.content|length > 150 %}
        <p class="half-content" id="half-{{post.id}}">{{ post.content|truncatechars:150 }}<a data-id="{{post.id}}" href="javascript:void();" class="show-hide-btn">read more</a></p>
        <p class="full-content" id="full-{{post.id}}" style="display: none;">{{ post.content }}</p></div>
    {% else %}
        <p>{{ post.content }}</p>
    {% endif %}
{% endfor %}


<script>
    $(document).ready(function(){
        $(".show-hide-btn").click(function(){
            var id = $(this).data("id");
            $("#half-"+id).hide();
            $("#full-"+id).show();
        });
    });
</script>

【讨论】:

  • 这太完美了!非常感谢您的帮助!
猜你喜欢
  • 2021-02-16
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2023-03-12
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多