我正在学习Javascript。 我已经达到了src和alt 。 我得到了这个例子,但我不明白这个例子中有什么意义。 有人可以解释一下吗? (第4和第5行)。 为什么函数Change()在最后再次执行?(完整代码)
function Change() { var first = document.getElementById('traffic'); var obj = list[next]; first.src = obj.src; first.alt = obj.src; timer = setTimeout(Change, obj.interval); nextlight = nextlight + 1; if (nextlight == list.length) nextlight = 0; }完整代码:
<!DOCTYPE html> <html> <body> <h1>JavaScript Code</h1> <p>Traffic Light</p> <img id="traffic" src="only red1.jpg"> <button type="button" onclick="Change()">Change Light</button> <script> var list = [{ src: "only red1.jpg", interval: 10000 }, { src: "red-yellow 2.jpg", interval: 5000 }, { src: "green3.jpg", interval: 3000 }, { src: "yellowonly4.jpg", interval: 1000 }]; var next = 0; var timer; function Change() { var first = document.getElementById('traffic'); var obj = list[next]; first.src = obj.src; first.alt = obj.src; timer = setTimeout(Change, obj.interval); next = next + 1; if (next == list.length) next = 0; } Change(); </script> </body> </html>所有的帮助表示赞赏,我只是想学习。
I'm currently learning Javascript. I have gotten to the point of src and alt. I was given this example but I don't understand what is the point of it in this example. Can someone explain, please? (lines 4 and 5). And why is the function Change() executed again at the end ?(full code)
function Change() { var first = document.getElementById('traffic'); var obj = list[next]; first.src = obj.src; first.alt = obj.src; timer = setTimeout(Change, obj.interval); nextlight = nextlight + 1; if (nextlight == list.length) nextlight = 0; }Full code:
<!DOCTYPE html> <html> <body> <h1>JavaScript Code</h1> <p>Traffic Light</p> <img id="traffic" src="only red1.jpg"> <button type="button" onclick="Change()">Change Light</button> <script> var list = [{ src: "only red1.jpg", interval: 10000 }, { src: "red-yellow 2.jpg", interval: 5000 }, { src: "green3.jpg", interval: 3000 }, { src: "yellowonly4.jpg", interval: 1000 }]; var next = 0; var timer; function Change() { var first = document.getElementById('traffic'); var obj = list[next]; first.src = obj.src; first.alt = obj.src; timer = setTimeout(Change, obj.interval); next = next + 1; if (next == list.length) next = 0; } Change(); </script> </body> </html>All help appreciated, I'm just trying to learn.
最满意答案
obj包含<img>元素,因此分配给obj.src和obj.alt更改图像显示的URL。 如果你这样做
obj.src = "green3.jpg";图像将显示绿灯。
该功能在结束时执行,以便它将进行第一次换灯,然后启动定时器,在几秒钟后再次更换它。
obj contains the <img> element, so assigning to obj.src and obj.alt changes URL that the image displays. If you do
obj.src = "green3.jpg";the image will show a green light.
The function is executed at the end so that it will do the first light change, and then start the timer that changes it again after a few seconds.
更多推荐
发布评论