Javascript getElementById数组
我正在制作一个表格,当你按下一个按钮时,表格中的一个随机单元格会改变它的背景色。我需要将带有Javascript getElementById数组,javascript,Javascript,我正在制作一个表格,当你按下一个按钮时,表格中的一个随机单元格会改变它的背景色。我需要将带有document.GetElementById的变量放入数组中,但它似乎不起作用。下面是我的代码: function setColor(){ var one = document.GetElementById('t1') var two = document.GetElementById('t2') var three= document.GetEleme
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";
}
您正在将字符串推入
单元格
,而不是元素
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
如果将字符串推入单元格数组,则这些对象与文档元素本身完全不同
cells.push(one);
cells.push(two);
cells.push(three);
是您想要的。您正在
单元格中添加字符串。使用以下命令:
cells.push(one);
cells.push(two);
cells.push(three);
尝试:
函数setColor(){
var one=document.getElementById('t1')
var two=document.getElementById('t2')
var三=document.getElementById('t3')
var单元格=[];
单元格。推送(一个值);
单元格。推送(两个值);
细胞。推(三。值);
var VALUETUSE=单元格[Math.floor(Math.random()*cells.length)];
valueToUse.style.backgroundColor=“红色”;
}
您可以省略数组,直接使用随机数来寻址元素
顺便说一句,getElementById
以一个小字母开头
function setColor() {
var randomNumber = Math.floor(Math.random() * 3) + 1,
element = document.getElementById('t' + randomNumber);
element.style.backgroundColor = "red";
}
getElementById
非getElementById
。JavaScript是区分大小写的。修复你的GetElementById
是的,我没有注意到tnx太多了:PFix你的GetElementById
tnx肯定会帮助我的代码看起来更好:P