Cannot set property 'backgroundColor' of undefined как исправить в массиве объектов?
Задача с лампами: в поле вводится кол-во лампочек, и после нажатия на кнопку они должны появиться и начать мигать. Проблема: при вводе больше 1 происходит ошибка
"Cannot set property 'backgroundColor' of undefined"
const divlamp = '<div id="lamp"></div>';
function Lamp(lamp, color, interval){
this.lamp = document.getElementById(lamp);
this.isOn = true;
this.color = color;
this.interval = interval;
this.switch = function(){
if(this.isOn==true){
this.lamp.style.backgroundColor = "red";
}else {
this.lamp.style.backgroundColor = "grey";
}
this.isOn = !this.isOn;
}
this.work = function(){
setInterval(this.switch, this.interval);
}
}
start = function(){
let lamps = [];
let kolvo = document.getElementById("kol").value;
for(let i=0; i<kolvo; i++){
document.getElementById("girlyand").insertAdjacentHTML("afterbegin",divlamp);
lamps.push(new Lamp("lamp","blue", 1000));
lamps[i].work();
}
}
#lamp{
height: 100px;
width: 100px;
border-radius: 50%;
background: grey;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<input id="kol"><button onclick="start()">OK</button>
<div id="girlyand">
</div>
</body>
</html>
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
const divlamp = '<div id="lamp"></div>';
function Lamp(lamp, color, interval) {
this.lamp = document.getElementById(lamp);
this.isOn = true;
this.color = color;
this.interval = interval;
this.switch = function() {
if (this.isOn == true) {
this.lamp.style.backgroundColor = "red";
} else {
this.lamp.style.backgroundColor = "grey";
}
this.isOn = !this.isOn;
}
this.work = function() {
setInterval(this.switch.bind(this), this.interval);
}
}
start = function() {
let lamps = [];
let kolvo = document.getElementById("kol").value;
for (let i = 0; i < kolvo; i++) {
document.getElementById("girlyand").insertAdjacentHTML("afterbegin", divlamp);
lamps.push(new Lamp("lamp", "blue", 1000));
lamps[i].work();
}
}
#lamp {
height: 100px;
width: 100px;
border-radius: 50%;
background: grey;
}
<input id="kol" value=3><button onclick="start()">OK</button>
<div id="girlyand"></div>