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;iconsole.log()
h
和w
来查看您实际查找的元素。必须有一些不存在的单元格。console.log(h,w,cell)
以及h
和w
单元格为空的调试。