Django项目使用JS实现评论功能时评论被多次追加的bug如何修复?
问题根因
每次点击Comment按钮触发comment(id)函数时,都会给同一个评论提交按钮新增一个点击事件监听器。多次打开评论框就会绑定多个重复监听器,提交时所有监听器会同时执行,因此第N次提交就会触发N次请求、追加N条重复评论。
之前尝试移除监听器未生效,是因为绑定用的是匿名函数,没有保存对应的函数引用,调用removeEventListener时无法匹配到要移除的目标监听器。
修复方案
方案1:添加once参数(改动最小)
给addEventListener添加第三个配置项{ once: true },监听器触发一次后会自动销毁,不会重复残留:
function comment(id) { document.querySelector(`#comment_box_${id}`).style.display = 'block'; document.querySelector(`#comment_button_${id}`).style.display = 'block'; document.querySelector(`#line1_${id}`).style.display = 'block'; document.querySelector(`#comment_${id}`).style.display = 'none'; document.querySelector(`#comment_box_${id}`).value="" // 仅修改这一行,添加{ once: true } document.querySelector(`#comment_button_${id}`).addEventListener('click', () => { fetch('/comment/' + id, { method: 'PUT', body: JSON.stringify({ post: document.querySelector(`#comment_box_${id}`).value }) }) .then((res) => res.json()) .then((res) =>{ var com = document.createElement('div'); com.innerHTML = `<p style="margin-left: 1cm;">${res.user} - ${res.content}</p> ` document.getElementById(`comment_list_${id}`).appendChild(com); document.querySelector(`#comment_box_${id}`).style.display = 'none'; document.querySelector(`#comment_button_${id}`).style.display = 'none'; document.querySelector(`#line1_${id}`).style.display = 'none'; document.querySelector(`#comment_${id}`).style.display = 'initial'; document.querySelector(`#comment_box_${id}`).value="" }) }, { once: true }); // 新增这部分配置 }
方案2:事件委托全局绑定(更规范)
把事件绑定逻辑从comment函数里移出去,页面加载时一次性绑定所有提交按钮的事件,避免重复绑定:
// 页面加载完成后全局绑定所有评论提交按钮的事件 document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('[id^="comment_button_"]').forEach(btn => { btn.addEventListener('click', () => { const id = btn.id.replace('comment_button_', '') fetch('/comment/' + id, { method: 'PUT', body: JSON.stringify({ post: document.querySelector(`#comment_box_${id}`).value }) }) .then(res => res.json()) .then(res =>{ const com = document.createElement('div'); com.innerHTML = `<p style="margin-left: 1cm;">${res.user} - ${res.content}</p> ` document.getElementById(`comment_list_${id}`).appendChild(com); document.querySelector(`#comment_box_${id}`).style.display = 'none'; document.querySelector(`#comment_button_${id}`).style.display = 'none'; document.querySelector(`#line1_${id}`).style.display = 'none'; document.querySelector(`#comment_${id}`).style.display = 'initial'; document.querySelector(`#comment_box_${id}`).value="" }) }) }) }) // 原有comment函数仅保留显隐切换逻辑,移除事件绑定代码 function comment(id) { document.querySelector(`#comment_box_${id}`).style.display = 'block'; document.querySelector(`#comment_button_${id}`).style.display = 'block'; document.querySelector(`#line1_${id}`).style.display = 'block'; document.querySelector(`#comment_${id}`).style.display = 'none'; document.querySelector(`#comment_box_${id}`).value="" }
额外后端问题修复
你的Python后端代码里post.save漏了括号,实际不会执行保存操作,需要修改为:
post.save()
内容的提问来源于stack exchange,提问作者mihilih
相关产品推荐
相关产品推荐

