JavaScript函数中条件语句问题:复选框切换文本失效排查
问题排查与修复
你的代码核心问题是JavaScript变量名大小写敏感:
- 你用
var checkbox = document.getElementById('check');定义了全小写的变量checkbox - 但在
if判断里误写成了checkBox(字母B大写),导致浏览器找不到该变量,函数无法正常执行
修正后的完整代码如下:
<script> function showconf() { var checkbox = document.getElementById('check'); if (checkbox.checked == true){ document.getElementById('show').value = "test"; } else { document.getElementById('show').value = "hello"; } } </script> <body> <input type="checkbox" id="check" onclick="showconf()"> <textarea id="show" name="message" rows="30" cols="100"></textarea> </body>
你也可以简化判断逻辑,直接利用三元表达式让代码更简洁:
<script> function showconf() { var checkbox = document.getElementById('check'); document.getElementById('show').value = checkbox.checked ? "test" : "hello"; } </script> <body> <input type="checkbox" id="check" onclick="showconf()"> <textarea id="show" name="message" rows="30" cols="100"></textarea> </body>
内容的提问来源于stack exchange,提问作者Kamel Abaza
相关产品推荐
相关产品推荐

