开发评论区遇TypeError:无法读取null的addEventListener属性
评论区功能报错解决及需求实现
问题详情
开发评论区功能时,需求为:评论输入框为空时发布按钮禁用,输入内容后按钮启用并变为蓝色。但运行时出现报错:
index.js:107 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
相关代码
报错的JavaScript代码
userComment.addEventListener("input", () => { publishBtn.disabled = !userComment.value.trim(); });
对应的HTML结构
<div id="StartComment" class="commentcontainer"> <div class="head"> <br><br><br><h1>Post a Comment!</h1> <a href="#publish">Click here to scroll down...</a> </div> <div> <span id="Comment">0</span> Comments </div> <div class="text"> <p>I will be happy to hear from you!</p> </div> <div class="comments"></div> <div class="commentbox"> <img src="commenterpng.png" alt="Commenter" id="CommenterStyle"> <div class="content"> <h2>Comment as:</h2> <input type="text" value="Anonymouse" class="user"> <div class="commentinput"> <input id="input" type="text" placeholder="Enter your comment..." class="usercomment"> <div class="buttons"> <button type="submit" id="publish" disabled>Publish</button> </div> </div> <p class="policy">This site is protected by reCAPTCHA and the Google <a href="#">Privacy Policy</a> and <a href="#">Terms of Service</a> apply. </p> </div> </div> </div>
解决方案
1. 修复addEventListener报错
报错核心原因是代码执行时找不到userComment或publishBtn元素,大概率是两个问题:
- JS代码在DOM元素加载完成前就执行了
- 获取元素的语句写错,没匹配到HTML里的对应元素
修正后的代码(确保DOM加载完成后执行,同时正确获取元素):
document.addEventListener('DOMContentLoaded', function() { // 可通过class或id获取输入框,二选一即可 const userComment = document.querySelector('.usercomment'); // const userComment = document.getElementById('input'); const publishBtn = document.getElementById('publish'); // 先判断元素是否存在,避免触发新报错 if (userComment && publishBtn) { userComment.addEventListener("input", () => { const hasContent = userComment.value.trim() !== ''; // 切换按钮禁用状态 publishBtn.disabled = !hasContent; // 切换按钮样式(两种方式选一种) // 方式1:内联样式直接修改 publishBtn.style.backgroundColor = hasContent ? 'blue' : '#ccc'; publishBtn.style.cursor = hasContent ? 'pointer' : 'not-allowed'; // 方式2:CSS类切换(更推荐,便于样式维护) // publishBtn.classList.toggle('active', hasContent); }); } });
2. 按钮变色的CSS方案(推荐)
如果选择CSS类的方式,先定义好样式:
#publish { background-color: #ccc; cursor: not-allowed; /* 可添加其他默认样式,比如边框、 padding 等 */ } #publish.active { background-color: blue; cursor: pointer; }
之后JS里只需要切换active类即可,代码更简洁易维护。
内容的提问来源于stack exchange,提问作者goatzy
相关产品推荐
相关产品推荐

