2013-02-01 23 views
13

可能重复:
Check if image exists with given url using jquery
Change image source if file exists检查,如果图像不存在使用JavaScript

我从一个文本框抛出图像路径的价值为boxvalue并要验证是否图像存在使用JavaScript。

var boxvalue = $('#UrlQueueBox').val(); 

我浏览了stackoverflow,发现下面的图片宽度/高度,但不想使用它。

var img = document.getElementById('imageid'); 

如何验证它是否真的是图像路径中的图像?

+4

看这个线程:HTTP ://fackipeflow.com/问题/ 5678899/change-image-source-if-file-exists –

+0

@FelipeOriani这是为了创造一个新的形象。 – X10nD

+0

你的问题到底是什么?我在你的文章中没有看到任何问号... – maerics

回答

47
// The "callback" argument is called with either true or false 
// depending on whether the image at "url" exists or not. 
function imageExists(url, callback) { 
    var img = new Image(); 
    img.onload = function() { callback(true); }; 
    img.onerror = function() { callback(false); }; 
    img.src = url; 
} 

// Sample usage 
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png'; 
imageExists(imageUrl, function(exists) { 
    console.log('RESULT: url=' + imageUrl + ', exists=' + exists); 
}); 
+0

这个测试创建一个新的图像,保存在Google Chrome浏览器的资源 - >图像下,无论这个url是否是一个有效的图像或不是我不特别喜欢的图像。 –

+1

这很好,但你能得到它返回的网址? 我有一个尝试为列表加载图标的循环,我需要的东西会返回您尝试的URL,或者如果图像不存在,则返回默认URL。所有的解决方案似乎运行一些代码或转储到控制台。 – chazthetic

5

您可以创建一个功能并检查complete属性。

function ImageExists(selector) { 
    var imageFound = $(selector); 

    if (!imageFound.get(0).complete) { 
     return false; 
    } 
    else if (imageFound.height() === 0) { 
     return false; 
    } 

    return true; 
} 

,并把这种功能可按

var exists = ImageExists('#UrlQueueBox'); 

的功能相同的URL,而不是选择的参数(你的情况):

function imageExists(url){ 

    var image = new Image(); 

    image.src = url; 

    if (!image.complete) { 
     return false; 
    } 
    else if (image.height === 0) { 
     return false; 
    } 

    return true; 
} 
+1

可以在没有#selector或#Id的情况下完成。我希望它直接从路径。 – X10nD

+0

可以在所有浏览器中工作,因为如果已经加载的图像被缓存,那么这将起作用。所以创建一个新的图像,只会加载已经缓存的图像。但是如果这个过程失败了,那么它将失败,这是缓存被禁用的情况。但仍然是一个很好的功能。 –

相关问题