在 javascript 中,图像必须随 var lvl 变化,但它不会
in javascript, image must change with var lvl, but it doesn't
我是 javascript 和网络编程的新手。
我正在尝试制作根据 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
,但是有问题-我点击按钮'try it!'后,图片变为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";
}
我是 javascript 和网络编程的新手。
我正在尝试制作根据 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
,但是有问题-我点击按钮'try it!'后,图片变为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";
}