首页 > 解决方案 > 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>

标签: javascript

解决方案


问题

元素的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")

推荐阅读