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

JavaScript字符串转变量实现单元格点击计数失效问题排查及修正

问题排查与修正方案

问题点分析

  • 变量赋值无效:你通过countx = 'count' + num得到了目标变量名的字符串,但之后直接给countx赋值1,只是修改了countx这个临时变量,并没有关联到全局的count1/count2/count3。全局变量在浏览器环境下挂载在window对象上,必须通过对象属性访问的方式才能修改。
  • 拼写错误:判断条件里的conunt3是笔误,应为count3。
  • 非法初始化调用:代码末尾的init(event)会在页面加载时执行,此时event对象不存在,直接触发报错,需删除。

修正方案(保留指定逻辑)

核心修改是将countx = 1替换为window[countx] = 1,利用window[变量名字符串]的方式访问并修改全局变量,完美保留你指定的let num = idname.charAt(idname.length-1); countx = 'count' + num逻辑。

修正后的完整代码

HTML

<div class="rows">
  <div class="cells" id="cell1" onclick="init(event)"></div>
  <div class="cells" id="cell2" onclick="init(event)"></div>
  <div class="cells" id="cell3" onclick="init(event)"></div>
</div>

CSS

body {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  position: relative;
}

* {
  margin: 0;
  box-sizing: border-box;
}

.rows {
  display: flex;
}

.cells {
  color: rgb(255, 255, 255);
  border: 1px solid rgb(44, 18, 236);
  font-size: 5rem;
  height: 6rem;
  width: 6rem;
  align-self: center;
  text-align: center;
}

JavaScript

var count1 = 0;
var count2 = 0;
var count3 = 0;

function init(event) {
  selectedcell();

  function selectedcell() {
    let idname = event.target.id;
    let num = idname.charAt(idname.length - 1);
    countx = 'count' + num
    console.log('countx = ', countx)
    // 关键修改:通过window对象访问全局变量
    window[countx] = 1;
    console.log(window[countx]);
  }

  console.log(count1);
  console.log(count2);
  console.log(count3);

  if (count1 == 1 && count2 == 1 && count3 == 1) {
    document.getElementById("cell1").style.backgroundColor = "green"
    document.getElementById("cell2").style.backgroundColor = "green"
    document.getElementById("cell3").style.backgroundColor = "green"
  }
}

内容的提问来源于stack exchange,提问作者eric2023

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:52:28