使用javascript检查图像是否存在 [英] Checking if image does exists using javascript

查看:124
本文介绍了使用javascript检查图像是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用jquery检查图像是否与给定网址一起存在

如果文件存在则更改图像源

我将图像路径的值从文本框扔到boxvalue,并想要使用javascript验证图像是否存在。

I am throwing the value of an image path from a textbox into boxvalue and want to validate if the image exist using javascript.

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

我浏览了stackoverflow并找到了下面的图片宽度/高度,但不想使用此。

I browsed stackoverflow and found the below to get the image width/height, but don't want to use this.

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

我如何验证它是否真的是来自图像路径的图像?

How can an I validate if it is really an image from the image path?

推荐答案

// 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);
});

这篇关于使用javascript检查图像是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆