我正在制作一个表格,当你按下一个按钮时,表格中的一个随机单元格会改变其背景颜色。我需要将带有document.GetElementById的变量放入数组中,但似乎不起作用。下面是我的代码:
function setColor(){
var one = document.GetElementById('t1')
var two = document.GetElementById('t2')
var three= document.GetElementById('t3')
var cells = [];
cells.push("one");
cells.push("'two'");
cells.push("three");
var valueToUse = cells[Math.floor(Math.random() * cells.length)];
valueToUse.style.backgroundColor = "red";
}发布于 2016-09-01 00:43:50
您正在cells数组中添加字符串。使用以下内容:
cells.push(one);
cells.push(two);
cells.push(three);发布于 2016-09-01 00:43:16
您正在将字符串推送到cells中,而不是元素中。
function setColor(){
var one = document.getElementById('t1')
var two = document.getElementById('t2')
var three= document.getElementById('t3')
var cells = [];
cells.push(one);
cells.push(two);
cells.push(three);
var valueToUse = cells[Math.floor(Math.random() * cells.length)];
valueToUse.style.backgroundColor = "red";
}同样,正如j08691所说,它是getElementById,而不是GetElementById。
发布于 2016-09-01 00:43:43
您正在将字符串推入单元格数组,这些字符串与文档元素本身是完全不同的对象。
cells.push(one);
cells.push(two);
cells.push(three);就是你想要的。
https://stackoverflow.com/questions/39254887
复制相似问题