在 JavaScript 中,图像必须随 VaR LVL 而更改,但它不会

in javascript, image must change with var lvl, but it doesn't

本文关键字:LVL VaR JavaScript 图像      更新时间:2023-09-26

我是javascript和Web编程的新手。我正在尝试制作脚本,该脚本将根据var lvl的值更改图像pic0.png

这是脚本:

<!DOCTYPE html>
<html>
<body>
<script>
    var pic = "pic0.png";
</script>
<img id="myImg" src="pic0.png" width="107" height="98">
<p>Click the button to change the value of the src attribute of the image.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() 
{
    var lvl = 2;
    if (lvl = 1)
    {
        pic = "pic1.png";
    }
    else if (lvl = 2)
    {
        pic = "pic2.jpg";
    }
    document.getElementById("myImg").src = pic;
}
</script>
</body>
</html>

var lvl等于2时,图片必须更改为pic2.jpg,但是有问题 - 在我点击按钮"尝试!"后,图片变为pic1.png,无论var lvl等于2还是1。

您正在分配值而不是检查。您需要使用双等号运算符:

function myFunction() 
{
  var lvl = 2;
  if (lvl == 1)
  {
    pic = "pic1.png";
  }
  else if (lvl == 2)
  {
    pic = "pic2.jpg";
  }
  document.getElementById("myImg").src = pic;
}

比较时应使用====== 是赋值运算符。

if (lvl == 1)
{
pic = "pic1.png";
}
else if (lvl == 2)
{
pic = "pic2.jpg";
}