【问题标题】:How to set src of image by a function call?如何通过函数调用设置图像的 src?
【发布时间】:2016-11-26 15:01:18
【问题描述】:

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

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

脚本是:

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

但它不起作用。

【问题讨论】:

    标签: javascript html image src


    【解决方案1】:

    你不能这样设置。

    您可以使用 javascript 更改值:

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

    【讨论】:

      【解决方案2】:

      你不能那样做。 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-12
        • 2018-07-14
        • 2017-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多