我在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}},但到目前为止,我所尝试的一切都是无效的。
试试这个,
{% 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>