表情反馈跳转页面控制台TypeError错误排查求助
问题原因
你在差评页(negative_review.html)及好评页中都引入了script.js,但这两个页面内既没有#send按钮,也没有评分相关的.rating元素。当脚本在这些页面执行时:
document.querySelector("#send")会返回null,调用addEventListener时就会触发Cannot read properties of null错误- 同理,
panelContainer绑定点击事件的代码也会因为页面中无对应交互元素出现潜在报错
解决方案
方案1:给DOM操作添加存在性判断(推荐)
修改script.js,在添加事件监听前先判断目标元素是否存在,避免在静态页面执行无效代码:
const sendButton = document.querySelector("#send"); const panelContainer = document.querySelector(".panel-container"); const ratings = document.querySelectorAll(".rating"); const removeActive = () => { for (let i = 0; i < ratings.length; i++) { ratings[i].classList.remove("active"); } }; // 仅在评分容器和评分元素存在时绑定点击事件 if (panelContainer && ratings.length > 0) { panelContainer.addEventListener("click", (e) => { if (e.target.parentNode.classList.contains("rating")) { removeActive(); e.target.parentNode.classList.add("active"); } }); } // 仅在发送按钮存在时绑定跳转事件 if (sendButton) { sendButton.addEventListener("click", () => { const experience = document.querySelector(".active small"); if (experience.innerHTML === "Unhappy" || experience.innerHTML === "Neutral") { window.location = "negative_review.html"; } else { window.location = "positive_review.html"; } }); }
方案2:拆分脚本或移除静态页面的JS引入
因为好评页和差评页是纯静态展示页面,不需要任何交互逻辑,直接删除这两个页面里的<script src="script.js"></script>标签即可,只在index.html中保留脚本引入。
内容的提问来源于stack exchange,提问作者DevelopingCoder
相关产品推荐
相关产品推荐

