如何使用功能动态设置IMG SRC



我想在JavaScript中设置img src=" ",该函数在变量上更改图片并检查值:

JavaScript文件代码:

 function myFunctionstatus(){
 var ledactual=document.getElementById("ledonof").value     
 var image = document.getElementById('ledPic'); 
 if (ledactual==ledon) {
     image.src = "https://cdncontribute.geeksforgeeks.org/wp-c 
  content/uploads/OFFbulb.jpg"; 
    }
 if (ledactual==ledoff){
     image.src = "https://cdncontribute.geeksforgeeks.org/wp- 
   content/uploads/ONbulb.jpg";
 }                    
   } };

img src在html文件中:

 <img id="ledPic" [src]="myFunctionstatus()" > 

,但它与我无效,图片没有出现!脚本正在工作,我用一个按钮进行了测试:

 <input type="button" id="ledonof"  onclick="myFunction();myFunctionstatus();" class="ledonoff" value="<?phpinclude ('ledstatus.php'); ?>">

如何使用功能设置IMG SRC?

我无法评论您用来获得状态的PHP,但以下是一个工作的JavaScript示例:

function myFunctionstatus(){
   var input = document.getElementById("ledonof");
   var image = document.getElementById('ledPic'); 
   if (input.value == "on") {
     image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
     input.value = "off"
   } else if (input.value == "off"){
     image.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg"; 
     input.value = "on"
   }                    
 }
 
 myFunctionstatus()
<img id="ledPic" /> 
 <input type="button" id="ledonof"  onclick="myFunctionstatus();" class="ledonoff" value="on">

正如其他人指出的那样,SRC不支持函数调用(甚至您甚至不会从功能调用中返回任何内容(,因此您需要在开始时一次运行该功能才能将图像设置为初始状态。

您需要手动设置初始状态

function switchStatus() {
  let switchButton = document.getElementById('ledonof');
  let img = document.getElementById('ledPic');
  if(switchButton.value == "ledon") {
    img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg";
    switchButton.value = "ledoff";
  } else {
    img.src = "https://cdncontribute.geeksforgeeks.org/wp-content/uploads/ONbulb.jpg";
    switchButton.value = "ledon";
  }
}
<img id="ledPic" src="https://cdncontribute.geeksforgeeks.org/wp-content/uploads/OFFbulb.jpg" > <input type="button" id="ledonof"  onclick="switchStatus();" value="ledoff">

img src attr不支持函数调用。无论您在SRC中传递的任何内容都将被视为URL(相对或其他方式(。请参阅https://developer.mozilla.org/en-us/docs/web/html/element/img#attributes

因此,您需要做的就是在加载元素之前调用该功能,然后更改SRC。最简单的形式将遵循

`<script>
(function() {
   // your page initialization code here
   // the DOM will be available here
   // call the function here
})();
</script>`

您不能这样做。解释HTML时,图像元素的SRC属性无法解释为JavaScript。

最初,您需要设置SRC,然后单击按钮,可以通过更改图像SRC切换图像。

最新更新