gpt4 book ai didi

javascript - 我的代码有什么问题?(使用 javascript 更改图片)

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:46 25 4
gpt4 key购买 nike

我希望点击两个按钮时图片从灯泡关闭变为灯泡打开。我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com