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 %}
添加回答
舉報