我希望通过单击两个按钮将图片从灯泡关闭变为灯泡打开。我在 W3schools 中看到过类似的示例,但是,我看不出代码之间的区别。请帮忙。
<!doctype html>
<html>
<body>
<script>
function light(switch){
var pi;
if(switch == 0){
pi = "pic_bulboff.gif"
}
<!--this is if the switch value is zero-->
else{
pi = "pic_bulbon.gif"
}
<!--this is if switch value is anything else including 1-->
document.getElementById('sw').src = pi;
}
</script>
<img id="sw" src="pic_bulboff.gif">
<button onclick="light(0)">Light off</button>
<button onclick="light(1)">Light on</button>
</body>
</html>
最佳答案
switch
is a reserved keyword which can not be used as argument name
function light(s) { //Change argument name
var pi;
if (s == 0) {
pi = "pic_bulboff.gif";
} else {
pi = "pic_bulbon.gif";
}
document.getElementById('sw').src = pi;
document.getElementById('sw').title = pi; //Just to demonstrate
}
<img id="sw" src="pic_bulboff.gif">
<button onclick="light(0)">Light off</button>
<button onclick="light(1)">Light on</button>
关于javascript - 我的代码有什么问题吗?(使用javascript更改图片),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37453602/