You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:54:22