使用forEach方法更改项目的属性(javascript)
问题描述:
我正在使用javascript forEach方法来迭代数组中的项目,但是当我尝试对项目执行某些操作时它会引发错误。使用forEach方法更改项目的属性(javascript)
在下面的代码中,当我控制台登录'item'时,它给出了日志'div1,div2,div3'到控制台的所需行为。但是,当我尝试对这些项目进行更改时,它不会允许它。在Google中使用forEach方法的例子非常抽象。
如何使用此方法更改项目的背景颜色或其他属性?
Codepen链接在这里https://codepen.io/emilychews/pen/boJBKB
JS
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = ['div1','div2','div3']
myArray.forEach(function(item){
console.log(item);
item.style.backgroundColor = "blue";
})
CSS
.div {height: 50px; width: 50px; background-color: red; margin-bottom: 10px;}
HTML
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>
任何帮助将是真棒
艾米莉
答
删除引号,如:var myArray = [div1,div2,div3]
答
您myArray
包含Strings
,不Dom Nodes
。 试试这个代码:
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = [div1,div2,div3]
myArray.forEach(function(item){
console.log(item);
item.style.backgroundColor = "blue";
})
该数组是字符串数组,而不是那些变量数组 –
将字符串''div1''等与指针'div1' –
谢谢帕特里克和Jonas。这确实奏效。 –