页面运行正常但控制台抛出Uncaught TypeError: Cannot read properties of null错误求助
解决"Cannot read properties of null (reading 'addEventListener')"错误
错误原因
你的JavaScript代码尝试获取的DOM元素(#send按钮、.ratings-container容器、.rating评分项、small文本标签)在当前HTML文件中完全不存在,导致document.querySelector/document.querySelectorAll返回null或空集合,调用addEventListener方法时触发类型错误。
解决方案
方案1:匹配DOM结构(推荐)
如果你的JavaScript是为评分选择页面编写的,当前HTML文件不符合代码逻辑,需要替换为包含对应元素的结构:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" /> <link rel="stylesheet" href="style.css" /> <title>Feedback</title> </head> <body> <div id="panel" class="panel-container"> <strong>How was your experience?</strong> <div class="ratings-container"> <div class="rating"> <i class="fas fa-star"></i> <small>Unhappy</small> </div> <div class="rating"> <i class="fas fa-star"></i> <small>Neutral</small> </div> <div class="rating"> <i class="fas fa-star"></i> <small>Satisfied</small> </div> </div> <button id="send">Send Review</button> </div> <script src="script.js"></script> </body> </html>
方案2:添加空值判断(适配当前HTML)
如果当前HTML是正确的页面,需要修改JS代码,先检查元素是否存在再绑定事件:
// const panel = document.querySelector("#panel"); const sendButton = document.querySelector('#send'); const ratingsContainer = document.querySelector('.ratings-container'); const ratings = document.querySelectorAll('.rating'); const experience = document.querySelectorAll('small'); const removeActive = () => { for (let i = 0; i < ratings.length; i++) { ratings[i].classList.remove('active'); } }; // 先判断容器是否存在再绑定点击事件 if (ratingsContainer) { ratingsContainer.addEventListener('click', (e) => { // 用可选链操作符避免e.target.parentNode为null的情况 if (e.target.parentNode?.classList.contains('rating')) { removeActive(); e.target.parentNode.classList.add('active'); } }); } // 先判断按钮是否存在再绑定点击事件 if (sendButton) { sendButton.addEventListener('click', () => { console.log(experience[0]); for (let i = 0; i < experience.length; i++) { if (experience[i].innerHTML === 'Unhappy' || experience[i].innerHTML === 'Neutral') { document.location.href = 'negative_review.html'; } else { document.location.href = 'positive_review.html'; } } }); }
内容的提问来源于stack exchange,提问作者DevelopingCoder
相关产品推荐
相关产品推荐

