所以,我可以让它从红色变为琥珀色,但我仍然坚持如何进一步让它变为绿色,再变为琥珀色然后再变红色。任何帮助将受到高度赞赏。
另外,我在dreamwaver上创造了这个。
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Traffic Lights </h1>
<img id="light" img src="../../red.jpg">
<button type="button" onClick="changeLights()">Change Lights</button>
<script>
function changeLights(){
document.getElementById('light').setAttribute("src","../../amber.jpg")
document.getElementById('light').setAttribute("src","../../green.jpg")
document.getElementById('light').setAttribute("src","../../amber.jpg")
//document.getElementById('light').setAttribute("src","../../red.jpg")
}
</script>
</body>
</html>
答案 0 :(得分:2)
最好的解决方案是将图像名称放入一个数组中,然后使用计数器循环遍历数组。该计数器可以根据我们上次命中的数组的“结束”来增加或减少计数。
此外,不要使用内联HTML事件处理属性(this
等),因为它们会创建“意大利面条代码”,它们会导致全局包装函数改变// Get references to DOM elements:
var img = document.getElementById('light');
var btn = document.getElementById('btn');
// Hook click of button up to event handling function
btn.addEventListener("click", changeLights);
// Put image names into an array:
var imgs = ["green.jpg" , "amber.jpg", "red.jpg"];
// Establish counter variable and directional variable
var count = 0;
var additive = 1;
function changeLights(){
// Set image by getting element from array based on current counter value
img.setAttribute("src","../../" + imgs[count]);
// Verification of action
console.clear();
console.log(img);
// When we hit the edges, reverse direction,
if(count === 2) {
additive = -1; // Go backward
} else if(count === 0) {
additive = 1; // Go forward
}
// Adjust the count accordingly
count+= additive;
}
绑定并且它们不会请遵循 W3C Event Model 标准。相反,使用 .addEventListener()
。
<h1>Traffic Lights </h1>
<img id="light" img src="../../red.jpg">
<button type="button" id='btn'>Change Lights</button>
SELECT *
FROM table_one 1
LEFT JOIN table_two 2 on 1.course = 2.course_list
LEFT JOIN table_two 3 on 1.course2 = 3.course_list
LEFT JOIN table_two 4 on 1.course3 = 4.course_list