使用jQuery实现视频动态评论时旧评论被统一覆盖如何解决
问题原因
- 你的代码里调用
$(".comment-content").text(comment)时,.comment-content是全局类选择器,会匹配页面中所有带该类名的元素,包括之前已经渲染完成的旧评论节点,所以每次新增评论时所有历史评论的内容都会被覆盖为最新的评论内容。
修复方案
调整新增评论的操作顺序:先创建新评论的DOM节点,仅对这个新节点内的评论内容赋值,再插入到评论列表中,就不会影响旧评论。
修复后的完整JS代码
$(document).ready(function() { $("#addCommentBtn").click(function() { var comment = $("#commentText").val(); if (comment === "") { $("#error-msg").fadeIn(); setTimeout(function() { $("#error-msg").fadeOut(); }, 3000); } else { // 先把新评论节点存为变量,此时还没插入到页面中 const $newComment = $('<li class="w-full comment mt-4"><div class="w-full md:w-1/2 comment flex flex-col"><div class="flex gap-4 items-center text-lg font-bold"><img src="assets/media/svg/NoPath - Kopya (75).png" class="rounded-full" alt=""><h1>André Potchinka</h1></div><div class="ml-16 flex flex-col justify-center"><div class=" mt-2 flex gap-1 items-center"><h1 class="comment-content text-gray-500 font-bold"></h1><span class="flex gap-2 -mt-1"><i class="fas fa-thumbs-up" aria-hidden="true"></i>0</span><span class="flex gap-2 -mt-1"><i class="fas fa-thumbs-down" aria-hidden="true"></i>0</span></div><div class="w-full flex flex-col"><input type="text" class="responseText border-b focus:outline-none bg-transparent mt-4" placeholder="Please login to leave a comment..."><ul class="responses p-4 flex flex-col gap-2"> </ul><button class="responseBtn text-right mt-2 text-gray-500">Answer</button></div></div></div></li>'); // 仅查找新评论节点内的内容区域赋值,不会影响旧评论 $newComment.find(".comment-content").text(comment); // 赋值完成后再插入到评论列表 $newComment.appendTo(".comments"); $("#commentText").val(""); $("#valid-msg").fadeIn(); setTimeout(function() { $("#valid-msg").fadeOut(); }, 3000); } }); });
额外优化建议
- 原有静态评论的内容节点可以统一加上
comment-content类,方便后续统一做样式或者逻辑控制 - 建议避免相同类名嵌套使用,你现有代码里li和内层div都用了
comment类,后续选择元素时容易出现匹配混乱的问题
内容的提问来源于stack exchange,提问作者user14201902
相关产品推荐
相关产品推荐

