【问题标题】:Read More js in django for loop在 django for 循环中阅读更多 js
【发布时间】:2021-08-17 18:11:49
【问题描述】:

我尝试应用此post 将阅读更多/阅读更少的 JS 集成到 django 模板中。我想限制我的帖子应用程序。 200 个字符,并为用户提供阅读更多内容的选项。

这个脚本似乎工作正常......在我的情况下不是那么多。 它显示“阅读更多”选项,但一旦单击它就不会触发任何事件。也就是说,它不会打开整个文本。它会显示一个彩色测试“阅读更多”,但会注意到其他情况。

这是post中提供的答案:

{% 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();
  

非常感谢您的任何意见。

【问题讨论】:

    标签: javascript django django-templates


    【解决方案1】:

    您需要显示其他即:full-content 当您单击 readmore 时,您可以使用 $("#full-" + id).toggle();。另外,我添加了 read less 文本来隐藏显示的文本。您可以添加该部分这里:

     <p class="full-content" id="full-{{post.id}}" style="display: none;">{{ post.content }}<a data-id="{{post.id}}" href="javascript:void();" class="show-hide-btn">read less</a></p>
    

    演示代码

    $(document).ready(function() {
      $(".show-hide-btn").click(function() {
        var id = $(this).data("id");
        $("#half-" + id).toggle();//hide/show..
        $("#full-" + id).toggle();
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <p class="half-content" id="half-1">Yes ,you..<a data-id="1" href="javascript:void();" class="show-hide-btn">read more</a></p>
    <p class="full-content" id="full-1" style="display: none;">Yes,you..are aweome<a data-id="1" href="javascript:void();" class="show-hide-btn">read less</a></p>
    <p class="half-content" id="half-3">Yes..you..<a data-id="3" href="javascript:void();" class="show-hide-btn">read more</a></p>
    <p class="full-content" id="full-3" style="display: none;">Yes ..you..can do it..<a data-id="3" href="javascript:void();" class="show-hide-btn">read less</a></p>

    【讨论】:

    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2020-11-21
    • 2016-02-02
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多