Jquery 如何影响django for循环中的单个条目?

Jquery 如何影响django for循环中的单个条目?,jquery,django,tags,truncate,Jquery,Django,Tags,Truncate,我在Django中创建了一个for循环,它显示用户上传的文章。对于长篇文章,我会将文本截断为150个字符的最大长度,但我想让读者通过单击“阅读更多”来选择使用jquery函数展开文本。 这是我的模板: {% for post in posts %} {% if post.content|length > 150 %} <p class="half-content">{{ post.content|truncatechars:150 }

我在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 %}
它按照我所希望的方式工作,除了“阅读更多”链接正在扩展页面上的所有文章,而不仅仅是带有适当主键的文章。我知道我需要在代码中的某个地方包含{{post.id}},但到目前为止,我所尝试的一切都是无效的。

试试这个

{% 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>
{%for posts in posts%}
{如果post.content |长度>150%}

{{post.content}truncatechars:150}

{{post.content}

{%else%} {{post.content}}

{%endif%} {%endfor%} $(文档).ready(函数(){ $(“.show hide btn”)。单击(函数(){ var id=$(this.data(“id”); $(“#一半-”+id).hide(); $(“#完整-”+id).show(); }); });
您可以使用javascript来实现这一点。谢谢,我已经编辑了我的问题,请在选择器上阅读。您应该将您的操作限制为具有“完整内容”的父元素的姐妹元素。或者你可以让自己轻松一点,只需给每个帖子一个id和推荐信就可以了。例如,您可以使用,也可以使用
{{{post.id}}
。感谢您的回复。我的帖子都已经有id了。你能告诉我在我的代码中应该在哪里包含{{post.id}吗?这太完美了!非常感谢你的帮助!
{% 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>