How to set src of image by a function call?

我们两清 提交于 2019-12-12 02:46:57

问题


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.


回答1:


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");



回答2:


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>


来源:https://stackoverflow.com/questions/29452233/how-to-set-src-of-image-by-a-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!