【问题标题】:replace a image in html with using of java script使用 java 脚本替换 html 中的图像
【发布时间】:2022-01-09 12:43:59
【问题描述】:

我不明白我在这里做错了什么,我尝试调试代码,但我没有发现我在这里做错了什么。 我尝试使用 java 脚本替换 html 中的图像,我希望能对我的问题提供一些有用的帮助

HTML 代码:

<img id = "lamp" src = "js/Capture.PNG"/>    
<!--make a button to turn on or off the lamp  in this case --> 

<button id = "off" name  = "offf" onclick="change_attribute()" >Turn off the light</button>
<button id = "on" name  = "offf" onclick="change_attribute()"> turn on the light </button> 
    

Javacript 代码:

function change_attribute() {
    var x = document.getElementsByName("offf");

    if (x.id === "off")
    {
        document.getElementById('off').src = "js/Capture.PNG/";
    }
    else
    {
        document.getElementById('on').src = 'js/Capture2.PNG/'
    }
    
}

【问题讨论】:

  • 不确定 C# 的相关性!

标签: javascript c# html css


【解决方案1】:

getElementsByName() 方法返回文档中具有指定名称的所有元素的集合。您正在尝试引用数组中不存在但实际数组元素上的 id 属性。

您可能应该重构您的代码以使用调用change_attribute() 的单个html 元素,它将分别在打开和关闭之间切换状态。

【讨论】:

    【解决方案2】:

    getElementsByName() 返回指定给定条件的 HTML 元素数组。

    在您的情况下,您将获得按钮 html 元素数组,因此,当您访问 x.id 时,它会给出错误,因为 x 是数组,而不是对象。

    尝试重构您的代码并仅从一个地方调用change_attribute

    【讨论】:

      【解决方案3】:

      function change_attribute(e) {
          if (e.target.id === "off")
          {
              document.getElementById('lamp').src = "https://cdn-icons-png.flaticon.com/512/2910/2910914.png";
          }
          else
          {
              document.getElementById('lamp').src = 'https://cdn-icons-png.flaticon.com/512/702/702797.png'
          }
          
      }
      #lamp{
      width: 50px;
      height: 50px;
      margin-right:15px;
      
      }
      <img id="lamp" src ="https://cdn-icons-png.flaticon.com/512/2910/2910914.png"/>    
      <!--make a button to turn on or off the lamp  in this case --> 
      
      <button id="off" class="lightBtn" onclick="change_attribute(event)" >Turn off the light</button>
      <button id="on"  class="lightBtn" onclick="change_attribute(event)"> turn on the light </button> 
          

      【讨论】:

      • 嗨@Warrior,如果这个或任何答案解决了您的问题,请点击复选标记考虑accepting it。这向更广泛的社区表明您已经找到了解决方案,并为回答者和您自己提供了一些声誉。没有义务这样做。
      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多