3 回答
TA贡献1797条经验 获得超6个赞
您无需使用 JavaScript 在每次迭代中更改 id。您可以使用 Django 的内置模板标签来实现相同的目的forloop.counter
。
所以在你的情况下,它会是这样的:
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<h2><a id="post_title_{{ forloop.counter }}" 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__{{ forloop.counter }}">
</p>
</img>
</div>
</div>
<p class="article-content">{{ post.content|truncatechars:200|safe }}</p>
</div>
</article>
{% endfor %}
TA贡献1777条经验 获得超3个赞
使用IIFE- IIFE(立即调用函数表达式)是一个 JavaScript 函数,一旦定义就运行。
<script>
(() => {
let a = document.getElementById('post_title');
a.setAttribute("id", 'post_title_1');
let b = document.getElementById('ViewCount');
b.setAttribute("id", 'ViewCount_1');
})();
</script>
TA贡献1865条经验 获得超7个赞
尝试使用document.getElementById('footer').setAttribute('id','post_title_1')
Also Make sure you are calling the changeid()function
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<h2><a id="post_title" 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>
<script>
function changeid ()
{
document.getElementById('post_title').setAttribute('id','post_title_1');
document.getElementById('ViewCount').setAttribute('id','ViewCount_1')
}
</script>
</article>
{% endfor %}
添加回答
举报