javascript - Javascript IF-Else not working as expected
问题描述
HI guys trying to learn javascript and been on w3schools...came across a try me that flipped the image right away from smiley.gif to landscape.jpg...so I decided I was going to see if I learned anything by flipping it with a button instead worked great...but then I decided that on each click I was going to make it go back and forth from smiley.gif to landscape and back to smiley etc... well thats when the frustration set in..I tried a million ways other then what I originally started with down in the code section...can someone explain to me why this doesnt work..I get no console errors...It still does the initial flip from smiley to landscape on first click but then never changes back to smiley on the second click. Thanks in Advance
<img id="image" src="smiley.gif" width="160" height="120"><br>
<button onclick= myFunc() >Click</button>;
<script>
function myFunc() {
if (document.getElementById("image").src == "smiley.gif") {
return document.getElementById("image").src = "landscape.jpg"
} else {
return document.getElementById("image").src = "smiley.gif"
}
};
</script>
<p>The original image was smiley.gif, but the script changed it to landscape.jpg</p>
解决方案
问题
元素的src
属性返回图像的完整路径,包括协议。
尽管您已将属性设置为smiley.gif
,但如果您设置console.log
为属性值,则类似于http://mywebsite.com/smiley.gif
. 显然,这不等于smiley.gif
。
使用src
属性:
console.log(document.getElementById("image").src);
<img id="image" src="test.jpg">
将来一定要采取这些基本的调试步骤。如果您的情况不正常,第一步是验证您比较的值是否符合您的预期。
解决方案
您不想使用属性,而是想从元素src
中检索src
属性。我们可以很容易地使用Element.getAttribute()
.
使用src
属性:
console.log(document.getElementById("image").getAttribute("src"));
<img id="image" src="test.jpg">
您的if
情况应如下所示:
if (document.getElementById("image").getAttribute("src") == "smiley.gif")
推荐阅读
- laravel - 如何在创建的 WordPress 中调用 API 路由
- javascript - Angular 6+ 中的透明包装器组件
- python - 调用自身内部的函数以使用 if 语句检查错误输入,if 语句永远不会中断和无限循环
- android - 如何将布局创建为从下方弹出的对话框
- service-worker - 不支持请求方法“POST”
- vba - 有没有办法在 MS Word VBA 中使用查找表?
- python - python3 subprocess.run() get 系统找不到Windows docker容器中指定的文件
- matlab - MATLAB图像处理缺失区域
- sql - 如何将列名导出到 redshift 中的文件
- lua - love2d 身体轮廓矩形