<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.box img {
width: 80px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
var box = document.querySelector("div.box");
var TrafficLight = function () {
this.color = 1;
this.dom = null;
this.init();
};
TrafficLight.prototype.init = function () {
this.dom = document.createElement("img");
this.dom.src = "./img/" + this.color + ".jpg";
box.appendChild(this.dom);
this.bindEvent();
};
TrafficLight.prototype.bindEvent = function () {
var that = this;
this.dom.onclick = function () {
that.changeColor();
};
};
TrafficLight.prototype.changeColor = function () {
this.color++;
if (this.color == 4) {
this.color = 1;
}
this.dom.src = "./img/" + this.color + ".jpg";
};
for (var i = 0; i < 100; i++) {
new TrafficLight();
}
</script>
</html>