How to set src of image by a function call?

2019-08-17 04:55发布

I want to set the src of an image to the return value of a function call. Here is what I am doing now:

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

and the script is:

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

But it doesn't work.

2条回答
欢心
2楼-- · 2019-08-17 05:24

You can't set it like that.

You can change the value with javascript:

<img id="image" src="picB.png" alt="can't display picture" />

document.getElementById("image").setAttribute("src","picA.png");
查看更多
地球回转人心会变
3楼-- · 2019-08-17 05:24

You can't do it that way. The src attribute doesn't interpret javascript.

You may do it like this:

<img id="picA">
<script type="text/javascript">
   function get_picAPath(){
      return "picA.png";
   }
   document.onload = function(){
      document.getElementById('picA').src= get_picAPath();
   };
</script>
查看更多
登录 后发表回答