【问题标题】:How to loop over an html with javascript?如何使用 javascript 遍历 html?
【发布时间】:2020-09-18 20:42:15
【问题描述】:

我有一个如下所示的 HTML 代码:-

<article class="media content-section">
    <div class="media-body">
        <h2><a class="article-title" href="{% url 'post-detail' post.slug %}">{{ post.title }}</a></h2>
        <div class="article-metadata">
            <a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a>
            <div class="float-right">
                <small class="text-muted">Category</small>
                <small class="text-muted">{{ post.date_posted }}</small>
            </div>
            <div style="float:right;">
                <img style="height:19px; width:18px;" src="{% static "blog/viewicon.png" %}">
                    <p style="float: right; display: inline !important;" id="ViewCount">
                     .....
                    </p>
                </img>
            </div>
        </div>
        <p class="article-content">{{ post.content|truncatechars:200|safe }}</p>
    </div>
</article>

我正在尝试将viewcount 的值异步添加到所有博客字段。使用这个 js/ajax 代码:-

<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

<script>
    $(document).ready(function(){

        setInterval(function()
        {
      $.ajax({
          type:'GET',
          url: "{% url 'getBlogs' %}",
          success: function(response){
          $("#ViewCount").empty();
          for (var key in response.blogs)
          {
              console.log(response.blogs);
              var temp = response.blogs[key].view_count
              $("#ViewCount").append(temp);
          }

          },
          error:function(response){
              alert("No Data Found");
          }
      });
        },1000);
    });
</script>

我有很多这样的博客,但是这些值似乎只在一个字段中同时显示,如下所示:-

但我试图将每个博客的viewcount 显示到其专用位置。有没有我无论如何都能做到的。

【问题讨论】:

    标签: javascript html django ajax


    【解决方案1】:

    最简单的方法之一是使用 HTML 标记来区分不同的 viewCount 使用数据属性。

    blogs={
        "1":{ 
        "view_count":1
      },
     "2": {
            "view_count":15
      }
    }
    for (var key in blogs)
     {
       var temp = blogs[key].view_count
       $(`[data-key=${key}]`).append(`${temp} views`);           
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p data-key="1" id="ViewCount">Key:1 :- </p>
    <p data-key="2" id="ViewCount">Key:2 :- </p>

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多