首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >getElementById数组

getElementById数组
EN

Stack Overflow用户
提问于 2016-09-01 00:41:09
回答 5查看 224关注 0票数 2

我正在制作一个表格,当你按下一个按钮时,表格中的一个随机单元格会改变其背景颜色。我需要将带有document.GetElementById的变量放入数组中,但似乎不起作用。下面是我的代码:

代码语言:javascript
复制
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";
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2016-09-01 00:43:50

您正在cells数组中添加字符串。使用以下内容:

代码语言:javascript
复制
 cells.push(one);
 cells.push(two);
 cells.push(three);
票数 1
EN

Stack Overflow用户

发布于 2016-09-01 00:43:16

您正在将字符串推送到cells中,而不是元素中。

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2016-09-01 00:43:43

您正在将字符串推入单元格数组,这些字符串与文档元素本身是完全不同的对象。

代码语言:javascript
复制
cells.push(one);
cells.push(two);
cells.push(three);

就是你想要的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39254887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档