如何通过函数调用设置图像的src

How to set src of image by a function call?

本文关键字:src 图像 设置 何通过 函数调用      更新时间:2023-09-26

我想将图像的src设置为函数调用的返回值。以下是我现在正在做的事情:

<img src="get_src()" alt="can't display picture" />

脚本是:

function get_picA() {
    return "picA.png";
}

但它不起作用。

不能这样设置。

您可以使用javascript:更改值

<img id="image" src="picB.png" alt="can't display picture" />
document.getElementById("image").setAttribute("src","picA.png");

你不能那样做。src属性不解释javascript。

你可以这样做:

<img id="picA">
<script type="text/javascript">
   function get_picAPath(){
      return "picA.png";
   }
   document.onload = function(){
      document.getElementById('picA').src= get_picAPath();
   };
</script>