[英]Issue with for cycle in django and javascript
I used django to try and make a replay of comments due their IDs. 我使用django尝试重播由于其ID而引起的评论。 Everything is working, but I can only get the last item from for cycle via javascript. 一切正常,但是我只能通过javascript从周期中获取最后一个项目。
{% for comment in object_comments %}
<li>
<article>
<div class="comment-avatar">
<img src="images/blog/author.png" class="avatar">
<span class="comment-reply">
<a id='reply' class="comment-reply-link" onClick="a_onClick()">Reply</a>
</span>
</div>
<script>
function button_onClick() {
$('').click();
}
function a_onClick() {
window.scrollTo(0,document.body.scrollHeight);
document.getElementById('text').value = "{{comment.name}}";
}
</script>
<div class="comment-body">
<div class="meta-data">
<a href="#" class="comment-author">{{ comment.name }}</a>
<span class="comment-date">
{{ comment.pub_date }}
</span>
</div>
<div class="comment-content">
{{ comment.text }}
</div>
</div>
</article>
</li>
{% endfor %}
The data is analyzed by document.getElementById('text').value = {{comment.name}};
通过document.getElementById('text').value = {{comment.name}};
分析数据document.getElementById('text').value = {{comment.name}};
Can someone help find some workaround? 有人可以帮忙找到解决方法吗?
The reason you're only getting the last value is that your <script>
function is inside the for loop, and so the code your Django loop is outputting contains this script code n number of times, using the same function name each time . 您仅获得最后一个值的原因是您的<script>
函数位于for循环内,因此Django循环输出的代码包含此脚本代码n次, 每次均使用相同的函数名称 。 So each definition “overwrites”, ie replaces, the previous one. 因此,每个定义都“覆盖”(即替换)先前的定义。 So the only definition of a_onClick()
that the browser's Javascript interpreter uses is the one for the final iteration of the loop, with the final {{ comment }}
in the loop. 因此,浏览器的Java语言解释器使用的a_onClick()
的唯一定义是循环的最后一次迭代的定义,循环中最后一个{{ comment }}
。
Your snippet doesn't include the #text
element that the function changes, so I can't follow it completely. 您的代码段不包含函数更改的#text
元素,因此我无法完全遵循它。 But to prevent the error you've described, first of all move your <script>
code outside the Django for-loop - place it after the loop instead, or at the end of the document body. 但是为了防止您描述的错误,首先将<script>
代码移到Django for循环之外-将其放置在循环之后或文档正文的末尾。 Then your function calls need to pass the correct comment.name
for each item in the loop. 然后,您的函数调用需要为循环中的每个项目传递正确的comment.name
。 You could do this inside the loop with: 您可以在循环中执行以下操作:
onclick="a_onClick('{{ comment.name }}')";
and then change your function to this: 然后将功能更改为此:
function a_onClick(comment_name) {
window.scrollTo(0,document.body.scrollHeight);
document.getElementById('text').value = comment_name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.