Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 循环中的getElementById不';我不能正常工作_Javascript_Html - Fatal编程技术网

Javascript 循环中的getElementById不';我不能正常工作

Javascript 循环中的getElementById不';我不能正常工作,javascript,html,Javascript,Html,我使用如下循环检查表格单元格: for (var h = i - 1; h < i + 2; h++) { for (var w = j - 1; w < j + 2; w++) { cell = document.getElementById('cell-' + (h).toString() + '-' + (w).toString()); console.log(cell.classList); } } for(var h=i-1;hconsole.lo

我使用如下循环检查表格单元格:

for (var h = i - 1; h < i + 2; h++) {
  for (var w = j - 1; w < j + 2; w++) {
    cell = document.getElementById('cell-' + (h).toString() + '-' + (w).toString());
    console.log(cell.classList);
  }
}
for(var h=i-1;h
我得到 类型错误:单元格为空

但是,当我使用数字而不是变量通过ID获取元素时,效果很好。例如:

for (var h = i - 1; h < i + 2; h++) {
  for (var w = j - 1; w < j + 2; w++) {
    cell = document.getElementById('cell-' + (1).toString() + '-' + (1).toString());
    console.log(cell.classList);
  }
}
for(var h=i-1;h

这部分代码有什么问题?如何使用循环遍历单元格?

在计算中尝试使用字符串文字。 根本不需要使用
toString()

函数getCell(){
对于(i=0;i我喜欢另一种解决方案,但是如果你对函数式编程感兴趣,你可能会或者可能不喜欢使用类似的东西。我知道已经有了一个有效的答案,但是对于我的解决方案,它都是函数式的

我的意思是,我不是来讨论你是否应该使用函数式编程而不是过程式编程,我只是提供一个替代解决方案

/*
window.getCells=()=>{
//获取HTMLCollection。
const cellCollection=document.querySelectorAll(“[id*=cell]”);
//转换为数组,以便我们可以使用映射。
const=Array.prototype.slice.call(cellCollection);
//现在打印每个项目。
map(i=>console.log(i));
};
*/
//基本上是一行,使用返回字符使其更可读。
window.getCells=()=>Array.prototype.slice
.call(document.queryselectoral(“[id*=cell]”)
.map(i=>console.log(i));


单击Me
i
j
(h)的初始值是多少。toString()
(1)。toString()
是无意义的,只需执行
一些字符串+一些数字
即可将其转换为字符串。它们也位于(var i=1;i很难说问题出在哪里,但这并不是因为您使用的是变量而不是数字文字。这将是因为您使用的数字错误。我们看不到您使用的是什么数字(我们不知道您的大多数变量的起始位置)或您应该使用的数字(我们看不到您的HTML)。您应该提供一个真实的。您还应该
console.log()
h
w
来查看您实际查找的元素。必须有一些不存在的单元格。
console.log(h,w,cell)
以及
h
w
单元格为空的调试。