Javascript 检查是否可以加载图像

Javascript 检查是否可以加载图像,javascript,jquery,html,Javascript,Jquery,Html,我想确定是否可以从服务器获取图像。将生成文件服务器的URL。我决定检查图像的自然高度。当我重新加载一个页面时,这段代码被剪掉了,但当我第一次尝试获取图像时,它就不起作用了。这是时间上的问题还是这段代码完全错了 <p id="buildingPh"></p> <script> $("#buildingPh").html("<img id='gebaeudeBild' width='100%' src='[image/url]'></

我想确定是否可以从服务器获取图像。将生成文件服务器的URL。我决定检查图像的自然高度。当我重新加载一个页面时,这段代码被剪掉了,但当我第一次尝试获取图像时,它就不起作用了。这是时间上的问题还是这段代码完全错了

<p id="buildingPh"></p>

<script>

    $("#buildingPh").html("<img id='gebaeudeBild' width='100%' src='[image/url]'></img>" );

    $( document ).ready(function() {
        if (document.getElementById("gebaeudeBild").naturalHeight == 0) {
            $("#buildingPh").html("No image found.");
        }
    });

</script>

$(“#buildingPh”).html(“”); $(文档).ready(函数(){ if(document.getElementById(“gebaeudeBild”).naturalHeight==0){ $(“#buildingPh”).html(“未找到图像”); } });

这是整个脚本。我使用的是AEM,因此不再需要代码了,因为您使用的是Jquery,请尝试将函数包装在Jquery的包装器中,以便文档就绪:

$(function () {

    if (document.getElementById("gebaeudeBild").naturalHeight == 0) {
        $("#buildingPh").html("No image found.");
    }
});

这只是一种预感,因为问题中没有提供太多细节。如果第一次获取图像时该函数不起作用,则在这里似乎是一个异步问题。

因为您使用的是Jquery,请尝试将该函数包装在Jquery的包装器中以备文档使用:

$(function () {

    if (document.getElementById("gebaeudeBild").naturalHeight == 0) {
        $("#buildingPh").html("No image found.");
    }
});

这只是一种预感,因为问题中没有提供太多细节。如果第一次获取图像时它不起作用,那么这里似乎是一个异步问题。

同意@lee2808,但我认为图像
加载
更适合处理图像错误事件

    $("#buildingPh").html("<img onerror='error()'  id='gebaeudeBild' width='100%' src='[image/url]'></img>" );

  function error() {
       $("#buildingPh").html("No image found.");    
        }; 
$(“#buildingPh”).html(“”);
函数错误(){
$(“#buildingPh”).html(“未找到图像”);
}; 

同意@lee2808,但我认为图像
加载
更适合处理图像错误事件

    $("#buildingPh").html("<img onerror='error()'  id='gebaeudeBild' width='100%' src='[image/url]'></img>" );

  function error() {
       $("#buildingPh").html("No image found.");    
        }; 
$(“#buildingPh”).html(“”);
函数错误(){
$(“#buildingPh”).html(“未找到图像”);
}; 

那么您正在使用其他代码来获取图像?当所有资产都已加载时,您是否在
document.ready()上运行此操作?您需要添加更多详细信息。请提供更多详细信息/代码。你是怎么得到这个图像的?它是通过异步方法实现的吗?您可以使用
.length
检查是否存在某些内容。例如,
如果($('#image').length){//ID确实存在,请执行一些操作}
那么您正在使用其他代码获取图像?当所有资产都已加载时,您是否在
document.ready()上运行此操作?您需要添加更多详细信息。请提供更多详细信息/代码。你是怎么得到这个图像的?它是通过异步方法实现的吗?您可以使用
.length
检查是否存在某些内容。例如,
如果($('#image').length){//ID确实存在,做点什么}
这不是一种生活吗?jQuery使用
document.ready()
在加载页面时运行。@PaulRedmond:jQuery有几种不同的方法来添加就绪处理程序,看这实际上是速记,这不是IIFE吗?jQuery使用
document.ready()
在加载页面时运行。@PaulRedmond:jQuery有几种不同的方法来添加就绪处理程序,请看这实际上是一种简写