0

我是 javascript 和整个网络编程的新手。我正在尝试制作将pic0.png根据var lvl' 值更改图像的脚本。

这是脚本:

<!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 时,图片必须变为,但是有问题 - 当我点击按钮“试试看!”后,无论等于 2 还是 1 pic2.jpg,图片都会变为。pic1.pngvar lvl

4

2 回答 2

2

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

function myFunction() 
{
  var lvl = 2;
  if (lvl == 1)
  {
    pic = "pic1.png";
  }
  else if (lvl == 2)
  {
    pic = "pic2.jpg";
  }
  document.getElementById("myImg").src = pic;
}
于 2015-12-16T09:54:58.263 回答
0

==或者===应该在比较时使用。=是赋值运算符。

if (lvl == 1)
{
pic = "pic1.png";
}
else if (lvl == 2)
{
pic = "pic2.jpg";
}
于 2015-12-16T09:55:14.117 回答