You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django站点JS获取循环元素comment_id重复问题求助

问题原因及解决方案:点击任意点赞按钮均返回第一条评论ID

错误原因

你在Django循环生成评论时,给每个点赞图标都设置了相同的id="chat-icon-thumbsup"。根据HTML规范,页面中每个元素的id必须是唯一的,而document.getElementById()方法只会返回DOM中第一个匹配该id的元素——这就是为什么不管点击哪个点赞按钮,弹窗都只显示第一条评论ID的核心原因。


解决方案

方法一:直接传递当前元素到点击函数

这是最直观的修改方式,适合快速修复:

  1. 修改HTML模板,在onclick事件中把当前点击的<i>元素传进去,同时去掉重复的id(既然不需要用id选择器,就没必要保留):
{% for comment_ in comments %}
<strong> 
  {{ comment_.name }} - {{ comment_.date_added }} 
  <button>
    <i comment_id="{{ comment_.comment_id }}" class="fa fa-fw fa-thumbs-up" title="like this comment" onclick="likeButton(this)"></i>
  </button> 
  {{ comment_.nr_of_likes }} <br/> 
</strong> 
{{ comment_.body }} <br/> 
{% endfor %}
  1. 调整JavaScript函数,直接使用传入的元素获取评论ID:
function likeButton(el) {
  alert(el.getAttribute("comment_id"));
}

方法二:使用事件委托(更推荐)

如果评论是动态加载的(比如后续分页加载新评论),事件委托会更灵活,不需要给每个新元素重复绑定点击事件:

  1. 给评论列表添加一个父容器(比如id="comments-container"),同时去掉每个点赞图标的onclick和重复id:
<div id="comments-container">
{% for comment_ in comments %}
<strong> 
  {{ comment_.name }} - {{ comment_.date_added }} 
  <button>
    <i comment_id="{{ comment_.comment_id }}" class="fa fa-fw fa-thumbs-up" title="like this comment"></i>
  </button> 
  {{ comment_.nr_of_likes }} <br/> 
</strong> 
{{ comment_.body }} <br/> 
{% endfor %}
</div>
  1. 给父容器绑定一次点击事件,通过事件冒泡判断点击的元素:
document.getElementById('comments-container').addEventListener('click', function(e) {
  // 确认点击的是点赞图标
  if (e.target.matches('.fa-thumbs-up')) {
    const commentId = e.target.getAttribute('comment_id');
    alert(commentId);
    // 这里可以添加发送点赞请求到后端的逻辑
  }
});

额外建议

HTML自定义属性推荐遵循data-*规范,比如把comment_id改成data-comment-id,这样更符合标准:

  • HTML中写成:data-comment-id="{{ comment_.comment_id }}"
  • JS中获取:el.getAttribute('data-comment-id') 或者更简洁的 el.dataset.commentId

内容的提问来源于stack exchange,提问作者NazaLearn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 19:10:18