点击网格元素修改其他区块属性时getElementById返回null求助
问题解决方法
你的核心问题出在getElementById()的使用上:这个方法接受的参数是纯ID名称字符串,不需要加CSS选择器里的#前缀。你代码里写了"#"+idWrap,导致找不到对应元素,所以返回null。
修正后的代码:
function getColor(cell) { var actual = document.getElementById(cell.id); var color = actual.style.background; var idWrap = actual.id.substr(0,3); alert("#"+idWrap); // 去掉#前缀,直接传ID名称 var element = document.getElementById(idWrap); // 先判断元素是否存在,避免报错 if (element) { element.style.backgroundColor = 'red'; // 也可以把获取到的网格颜色直接赋值过去 // element.style.backgroundColor = color; } }
额外补充两个实用细节:
- 变量记得用
var/let/const声明,避免全局变量污染(你原代码里的color和idWrap未声明)。 - 如果网格元素的背景色是通过CSS类设置的,
actual.style.background可能拿不到值,这时候可以用getComputedStyle(actual).backgroundColor获取实际生效的颜色。
内容的提问来源于stack exchange,提问作者arp9
相关产品推荐
相关产品推荐

