[英]How to loop over an html with javascript?
I have an HTML code which looks like this:-我有一个看起来像这样的 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>
I am trying to add the values of viewcount
asynchronously to all the blogs field.我正在尝试将viewcount
的值异步添加到所有 blogs 字段。 With this js/ajax code:-使用此 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>
I have many such blogs, But the values seem to be displayed all at once at only a single field which looks like this:-我有很多这样的博客,但这些值似乎只在一个字段中一次性显示,如下所示:-
But I am trying to display the viewcount
of each blogs to its dedicated position.但我试图将每个博客的viewcount
显示到其专用位置。 Is there I anyway I can achive it.反正我能做到吗?
One of the easiest way is to use HTML markup to differentiate different viewCount
using data attributes.最简单的方法之一是使用 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.