【问题标题】:image loads but does not update图像加载但不更新
【发布时间】:2022-12-03 08:11:35
【问题描述】:

我对 javascript 没有什么经验,我正在尝试更新图像,但没有成功。此图像来自 API,但图像未更新

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">

 function atualizarqr() {
  document.getElementById("img").src = "<?= $this->admin_m->qr_whatsapp(); ?>";
}

window.onload = function () {
  setInterval(atualizarqr(), 5000);
};
</script>


<div onload="atualizarqr">
<img src="" id="img"/>
</div>

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

    要更新图像,您可以尝试对代码进行以下更改:

    添加对 atualizarqr 函数的 setInterval 调用,它将每 5 秒更新一次图像。 使用 $ 语法访问 jQuery 库并使用 attr 方法设置 img 元素的 src 属性。 这是具有这些更改的代码的更新版本:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <script type="text/javascript">
    function atualizarqr() {
      // use jQuery to set the src attribute of the img element
      $("#img").attr("src", "<?= $this->admin_m->qr_whatsapp(); ?>");
    }
    
    window.onload = function () {
      // update the image every 5 seconds
      setInterval(atualizarqr, 5000);
    };
    </script>
    
    <!-- remove the onload attribute from the div element -->
    <div>
      <img src="" id="img"/>
    </div>

    在此更新的代码中,使用 setInterval 函数每 5 秒调用一次 atualizarqr 函数。此函数使用 jQuery 将 img 元素的 src 属性设置为 API 提供的图像的 URL。这将导致图像每 5 秒更新一次。

    请注意,从 div 元素中删除了 onload 属性,因为此属性用于指定页面加载时要调用的函数,在本例中不需要。

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 2013-05-30
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多