加载前检查图像是否存在 [英] Check if image exists before loading
问题描述
我使用了其他各种Stack Overflow问题中的示例,由于某种原因,这对我不起作用.我做了一个获取缩略图的函数,然后返回实际的图像路径或默认(无缩略图)图像的路径.
I've used examples from various other Stack Overflow questions and for some reason this is not working for me. I made a function to get thumbnail images and return either the actual image path or the path to the default (no thumbnail) image.
同时使用JQuery方法和Javascript Image类,由于控制台中缺少图像,我收到404错误,发现的图像没有错误但没有显示.谁能指出我做错了什么?
Using both the JQuery approach as well as the Javascript Image class, I get 404 errors regarding missing images in console and the found images don't error but don't show up. Can anyone perhaps point out what I am doing incorrect?
在getThumbnail()函数中,写入控制台时,"image_url"显示正确.当我在调用函数中并记录返回值时,它只是显示为"undefined".
In the getThumbnail() function the "image_url" when written to console appears correct. When I am in the calling function and log the returned value, it just appears as "undefined".
jQuery:
function getThumbnail(name)
{
var image_url = "images/" + name + ".jpg";
$.get(image_url)
.done(function()
{
return image_url;
})
.fail(function()
{
return "images/default.jpg";
})
}
JavaScript:
Javascript:
function getThumbnail(name)
{
var image = new Image();
image.src = image_url;
image.onload = function()
{
return image;
}
image.onerror = function()
{
return "images/default.jpg";
}
}
调用函数:
$.each( cycle, function( key, value )
{
var mapIndex = key;
var mapValue = value;
var brick = "<div class='brick small'><a class='delete' href='#'>×</a><img src='" + getThumbnail(value) + "' /><h2><span>" + value + "</span></h2></div>";
$( ".gridly" ).append( brick );
});
推荐答案
不起作用的问题是getThumbnail()方法将无法正常运行.
The problem it does not work is getThumbnail() method will not behave as you want.
.onload是一个异步调用,在这种情况下,getThumbnail(value)将始终具有未定义的返回结果;
The .onload is an async call and for this case, getThumbnail(value) will always have undefined returned result;
要完成所需的操作,可以执行以下操作:
To accomplish what you want, you can do something like:
<img src="/image/..." onerror="javascript:this.src='images/default.jpg'"/>
这篇关于加载前检查图像是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!