网页字数统计功能报错:Uncaught ReferenceError: countWord未定义
问题排查与解决方案
报错原因:countWord is not defined
这个错误的核心是页面触发onkeyup事件时,countWord函数还未被定义,或者不在全局作用域中,常见诱因是JS代码的加载时机不对。
具体问题拆解
- JS加载时机错误:如果你的JavaScript代码写在
<head>标签里,或者写在<textarea>元素之前,浏览器解析到<textarea>的onkeyup="countWord()"时,countWord函数还没被解析,自然找不到它。 - 字数统计逻辑有缺陷:用
split(" ")分割文本,遇到连续空格、换行符时会生成空字符串,导致统计结果失真(比如输入"hello world"会被算成4个词,而非正确的2个)。
修复步骤
1. 调整JS代码加载位置
把JS代码放在</body>标签的前面,确保页面所有DOM元素加载完成后再执行JS,这样getElementById能正确获取元素,函数也会被提前定义好。
2. 修正字数统计逻辑
用正则表达式匹配所有非空白字符的序列,准确统计单词数量,同时处理空文本的边界情况。
修正后的完整代码
<form class="contact-form" onsubmit="sendEmail(); reset(); return false;"> <h3>Get In Touch!</h3> <input type="text" id="name" placeholder="Name *" required> <input type="email" id="email" placeholder="Email *" required> <input type="number" id="phone" placeholder="Phone Number (Optional)" > <textarea id="txt" rows="4" placeholder="Message..."></textarea> <div class="row mt-3"> <div class="col"> Word Count: <span id="wordCount">0</span> </div> </div> <button id="clearBtn" type="submit">Send message</button> </form> </section> <!-- JS代码放在body结束标签前 --> <script> const textField = document.getElementById("txt"); const wordCount = document.getElementById("wordCount"); const clearBtn = document.getElementById("clearBtn"); function countWord(){ let text = textField.value.trim(); // 处理空文本的情况 if (!text) { wordCount.innerText = 0; return; } // 用正则匹配所有非空白字符的序列,排除连续空格、换行等干扰 let words = text.match(/\S+/g); wordCount.innerText = words.length; } // 替换内联事件,用事件监听器覆盖所有文本变化场景 textField.addEventListener('input', countWord); </script>
额外优化说明
上面的代码用addEventListener替代了内联的onkeyup和onpaste,input事件会自动响应键盘输入、粘贴、拖拽等所有文本变化场景,代码更简洁易维护。
内容的提问来源于stack exchange,提问作者Cheyenne
相关产品推荐
相关产品推荐

