HTML表单输入判断失效:输入hello提交后无法更新文本如何修复
故障原因
功能未正常触发的核心问题是取值逻辑错误:document.getElementById('thesearchh')获取到的是textarea的DOM元素对象,不是用户输入的文本内容,DOM对象不存在字符串专属的includes()方法,判断逻辑永远无法成立。
修复要点
- 获取输入框内容时,需要在DOM元素后追加
.value属性,拿到用户输入的实际字符串后再做匹配判断 includes()方法本身就会返回布尔值,不需要额外和true做相等比较,直接写入if条件即可
修复后可运行完整代码
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <textarea id="thesearchh" style="resize: none;"></textarea> <button onclick="submitSearch()">Submit</button> <p id="searchResult">hi</p> <script> function submitSearch() { if(document.getElementById('thesearchh').value.includes('hello')) { document.getElementById('searchResult').innerHTML = 'good job'; } } </script> </body> </html>
内容的提问来源于stack exchange,提问作者JaecadeJnight
相关产品推荐
相关产品推荐

