繁体   English   中英

Javascript 为 html 中的每个迭代元素返回相同的 id

[英]Javascript returns the same id for every iterated element in html

我有一个使用 Django 建立的网站,每个访问者都可以在其中留言或在任何评论上按赞按钮。 我想显示用户喜欢了多少条评论。 由于每个评论都是唯一的,我想访问我在 html 部分中编写的 comment_id 属性。 然后我使用一个简单的 js function 来检索 id。 问题是,虽然 html 显示了每个评论的唯一 ID,但 Javascript 仍然返回相同的 ID,即页面上写的第一条评论的 ID。 有人可以告诉我在这种情况下我的错误在哪里吗? 预先感谢您的帮助。

我在 js 中的代码: function likeButton(){ let el = document.getElementById("chat-icon-thumbsup") alert(el.attributes["comment_id"].value) };

我的 html 代码,它循环记录来自 Django 框架中数据表的数据表“评论”: {% for comment_ in comments %} <strong> {{ comment_.name }} - {{ comment_.date_added }} <button><i comment_id="{{ comment_.comment_id }}" id="chat-icon-thumbsup" class="fa fa-fw fa-thumbs-up" title="like this comment" onclick="likeButton()"></i></button> {{ comment_.nr_of_likes }} <br/> </strong> {{ comment_.body }} <br/> {% endfor %}

图 1:在这里你看到当我检查 DOM 元素时,它检索到不同的“comment_id” enter image description here image 2 和 image 3:在注释行中按下的每个按钮都提示相同的 id,即 16 enter image description here

我试图用谷歌搜索任何可能的相同问题,但没有找到解决方案

在 HTML 中,每个页面上的 ID 应该是唯一的。 因此,JS 只会返回它找到的具有该 ID 的第一个字段。 您应该使用的是定义您的字段的类名,例如:

<i id="comment_{{ comment_.comment_id }}" class="fa fa-fw fa-thumbs-up chat-icon-thumbsup" ....>

然后你可以使用document.getElementsByClassName("chat-icon-thumbsup") ,这就是为什么它被称为 getElementById 作为单数而不是 getElement s ById

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM