【问题标题】:Javascript: Detect an image's loading status, and only swap out the old image when the new one is 'loaded'?Javascript:检测图像的加载状态,仅在“加载”新图像时更换旧图像?
【发布时间】:2010-07-30 02:25:04
【问题描述】:

我调用了一个为我生成图形图像的 PHP 脚本,但是这需要几秒钟。有没有办法在用户端检测它何时完成加载,并且仅在 php 脚本完成并且图像准备好时才将其与旧图像交换?

这是我用来调用 PHP 脚本的 Javascript 函数:

编辑(代码已更新)

function loadGraph(self,graph,varID) {
    var img = new Image();

    img.onload = function() {
        $(self).parents().parents().siblings(".graph_container").empty().append(img);
    };

    img.src = 'drawGraph.php?type=journey_report&graph=' + graph +
        (varID != null ? '&amp;varID=' + varID : '') + '&amp;companyID=<?php echo $_SESSION['companyID'] ?>';   
}

这是图形容器和使用该功能的链接:

<div class="graph_container">
                        <img src="drawGraph.php?type=journey_report&graph=outOfDate_vs_upToDate&companyID=<?php
                            echo $_SESSION['companyID'] ?>" />
                    </div>

                    <div class="reportItemWrapper">
                        <div class="reportItem"><a href="#" onclick="loadGraph(this,'outOfDate_vs_upToDate'); return false"><b>Total</b></a></div>

谢谢!

【问题讨论】:

  • 我很困惑;那东西不起作用吗?我承认我没有尝试过......如果有错误或什么让我知道,我会看看我能做什么!

标签: javascript jquery


【解决方案1】:

创建一个 Image 对象并将其“onload”处理程序设置为执行您在第一个代码块中执行的操作的函数。然后将其“src”属性设置为您的 URL。

var img = new Image();
img.onload = function() {
  // that jQuery stuff
};
img.src = "drawGraph.php?type=journey_report ...";

现在只有在 URL 可缓存的情况下才有效。如果没有,那么您可以重新编写该 jQuery 代码,以便将 Image 元素填充到 DOM 中。

$(self).parents().parents().siblings(".graph_container").empty().append(img);

(您仍然可以在 onload 处理程序中执行此操作。)

【讨论】:

  • 嗯,好吧,你能告诉我是否正在获取图像数据吗?
  • 我想我不需要 &,只有 &,因为我将其作为 $_GET 数据:$_GET Array [4] type (string:14) journey_report amp;graph (string:21) outOfDate_vs_upToDate amp;varID (string:2) 41 amp;companyID (string:4) 1005
  • 好吧,我做了一个简单的测试 - 尝试将append(img) 更改为append($(img)) - 我将看看这是否会有所不同
  • 哦,现在我明白你在说什么了——是的,你不需要对 URL 字符串中的“&”字符进行 HTML 编码。只需使用普通的 &。
猜你喜欢
  • 2014-03-25
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多