在 JavaScript 中,图像必须随 VaR LVL 而更改,但它不会
in javascript, image must change with var lvl, but it doesn't
我是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";
}
相关文章:
- 控制台返回var不是't定义,但它是
- 从var向代码隐藏函数传递值
- 如何通过引用var Using DataTables来进行分页或排序
- jQuery语法添加了var
- 如何将具有文本类型值的var放入jQuery函数中
- JS:检查URL中的参数,然后迭代一个参数为var的函数
- 当var==0时,我如何显示一个警报
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- JavaScript-的含义:var DndUpload=函数(inputElem){};
- Understanding Javascript scope with "var that = this&qu
- 如何使用javascript var引用Mongo DB集合's字段
- var w = q||问2;这个表达式是什么意思
- 为什么JavaScript抛出'未捕获的ReferenceError:var未定义'定义var时
- 在jquery函数内部设置来自jquery函数的var;t运行
- 确定var是否是javascript中的elementFinder对象的方法是什么
- 如何使用var名称调用JSON数据
- '这'在使用之前分配给了一个var
- 更改json/javascript对象var名称或从数字var中检索值
- 在 JavaScript 中,图像必须随 VaR LVL 而更改,但它不会