javascript - 如何使用函数动态设置 img src

标签 javascript html image button

我想使用 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";
 }                    
   } };

html 文件中的 img src:

 <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不支持函数调用(并且您甚至不会从函数调用中返回任何内容),因此您需要在开始时运行该函数一次以将图像设置为初始状态。

关于javascript - 如何使用函数动态设置 img src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56237849/

相关文章:

javascript - 如何将 JavaScript 变量值传递给 python 变量(flask)

javascript - document.body.clientHeight 报告的高度比预期小得多

html - 在 Web 应用程序中更改 css 文件

php - 切换 JQuery slider - 默认值为 50%

android - 如何在 Android 中为位图着色?

javascript - 将日期转换为天数然后做一些事情

JavaScript 插件帮助 - ContentFlow

html - 过渡方向 - 边界

java - 自定义滚动条箭头

c# - 如何将图像类型转换为位图