关于javascript onclick foreach函数
我想为一个特定的帖子id显示一个foreach帖子的formonclick函数。我试着这样做,但它不起作用关于javascript onclick foreach函数,javascript,Javascript,我想为一个特定的帖子id显示一个foreach帖子的formonclick函数。我试着这样做,但它不起作用 {% for post in posts %} <div post-id="{{ post.id }}" class="post-box w3-container w3-card-2 w3-white w3-round w3-margin"><br> {# <img src="w3im
{% for post in posts %}
<div post-id="{{ post.id }}" class="post-box
w3-container w3-card-2 w3-white w3-round w3-margin"><br>
{# <img src="w3images/avatar6.png" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"> #}
<span class="w3-right w3-opacity">{{ post.created }}</span>
<h4>{{ user.name }}</h4><br>
<hr class="w3-clear">
<p><a href="/posts/{{ post.id }}">{{ post.title }}</a></p>
{# <img src="w3images/nature.jpg" style="width:100%" class="w3-margin-bottom"> #}
<p>{{ post.description }}</p>
<button type="button" class="w3-button w3-theme-d1 w3-margin-bottom"><i class="fa fa-thumbs-up"></i> Like</button>
<button class="w3-button w3-theme-d2 w3-margin-bottom" id="comment"><i class="fa fa-comment"></i>Comment</button>
<div id="comment-form-{{ post.id }}" style="display: none;">
<textarea></textarea>
<button type="button"></button>
</div>
</div>
{% endfor %}
<script>
var postBoxes = document.getElementsByClassName('post-box')
postBoxes.forEach(function (postBox) {
var postId = postBox.getAttribute('post-id')
postBox.onclick = function () {
document.getElementById('comment-form-' + postId).style.display = 'block'
}
})
</script>
{%for posts in posts%}
{# #}
{{post.created}}
{{user.name}}
{# #}
{{post.description}}
像
评论
{%endfor%}
var postboxs=document.getElementsByClassName('post-box')
邮箱.forEach(函数(邮箱){
var postId=postBox.getAttribute('post-id')
postBox.onclick=函数(){
document.getElementById('comment-form-'+postId.).style.display='block'
}
})
像这样更改您的代码。在单击事件中声明帖子id。使用。更改选择器,并使用,而不是普通的单击
工作示例
var postboxs=document.querySelectorAll('.postbox')
邮箱.forEach(函数(邮箱){
postBox.addEventListener('click',function(){
var postId=this.getAttribute('post-id')
控制台日志(postId)
document.getElementById('comment-form-'+postId.).style.display='block'
})
})
{
{{post.created}}
{{user.name}}
{# #}
{{post.description}}
喜欢
评论