简体   繁体   English

通过 JavaScript 更改 Src 属性

[英]Change Src attributes by JavaScript

There is an example on the w3shool site how to change picture (src attribute) by clicking 2 button. w3shool 网站上有一个示例,如何通过单击 2 按钮更改图片(src 属性)。 One of them is Light On, other is Light Off.其中一个是 Light On,另一个是 Light Off。

But, I want change picture by 1 button.但是,我想通过 1 个按钮更改图片。 (On and Off button). (开和关按钮)。 I wrote some code, but doesn't work.我写了一些代码,但不起作用。 Can anyone show me, where is my mistake?谁能告诉我,我的错误在哪里? My code:我的代码:

<body>

  <img id="myImage" src="/img/pic_bulboff.gif" width="100" height="180">
  
  <p>
  <button type="button" onclick="light()">Light On/Off</button>
  
  </p>
  
  <script>
  function light() {
  if (document.getElementById("myImage").src =="/img/pic_bulbon.gif") {
  document.getElementById("myImage").src == "/img/pic_bulboff.gif"
  } else {
   document.getElementById("myImage").src == "/img/pic_bulbon.gif"
    }
   } 
  </script>
  
  </body> 

Pictures: enter image description here enter image description here图片:在此处输入图像描述 在此处输入图像描述


    <img id="myImage" src="img/pic_bulboff.gif" width="100" height="180" />
    <script>
        const img = document.getElementById("myImage");
        // Paths
        const relPath = "img/pic_bulboff.gif";
        const absPath = img.src.slice(0, -relPath.length);
        console.log(img.src);
        console.log(absPath);

        function light() {
          //if (img.src == absPath + "img/pic_bulbon.gif") {
            if (img.src.includes("img/pic_bulbon.gif")) {
                img.src = "img/pic_bulboff.gif";
            } else {
                img.src = "img/pic_bulbon.gif";
            }
        }
    </script>

It doesn't work because.src returns the absolute path so comparing it with relative one won't work.它不起作用,因为 .src 返回绝对路径,因此将其与相对路径进行比较是行不通的。 You can extract it like in the example above or you can just use.includes() to check for a substring.您可以像上面的示例中那样提取它,或者您可以只使用.includes() 来检查 substring。 Notice that I removed the first / from src, you might need to add it back.请注意,我从 src 中删除了第一个 /,您可能需要将其添加回来。

As @Tushar mentioned mind to use single =, also you are likely missing the "."正如@Tushar 提到的使用单个 = 的想法,您也可能错过了“。” at the image src.在图像源。 It is usually like this通常是这样的

"./img/pic_bulbon.gif"

Then you can change the image src by:然后您可以通过以下方式更改图像 src:

document.getElementById("imageId").src="./img/pic_bulbon.gif";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM