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

标签 javascript html

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

相关文章:

javascript - JQuery 将 2 个输入框的值添加到第三个

javascript - 使用 JavaScript : prevent application inside DIV 在运行时编辑 CSS(更改选择器)

javascript - 如何四舍五入到小数点后两位?

html - 识别 URL 查询字符串中的内容定义键

html - 如何用进度条填充透明图像? #CSS #HTML #Jquery?

html - 在 header 标签末尾添加一条黑色长线

javascript - 如何在html静态页面中停止页面加载

javascript - Knockout 间歇性地将元素与 [object HTMLDivElement] 绑定(bind)

html css div 元素没有按我的预期显示 - 按照教程

html - Google map 未显示在 "row"类中