如何使用JavaScript检查图像URL为404 [英] How to check image url is 404 using javascript
本文介绍了如何使用JavaScript检查图像URL为404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用例:
- 当src不为null且alt标签不为null时,则显示src的图像.
- 然后检查src图片网址不是404.
- 当src为null且alt不为null时,名字的显示图像.
- 当src和alt为null时,则显示默认图片
HTML:
<img class="imagelazy" id="lazyimage" src="http://url" alt="ankit">
Javascript:
function imagelazy() {
$(document).ready(function()
{
var image = $(".imagelazy").attr('src');
var altdata = $(".imagelazy").attr('alt');
var alt = $(".imagelazy").attr('alt').split("");
//var imagepath="http://im.gifbt.com/userimages/"+alt[0].toLowerCase()+".jpg";
var defaultimage = "http://im.gifbt.com/img/no-pic.jpg";
console.log(image);
console.log(alt);
$(".imagelazy img")
.error(function() {
$(this).hide();
})
.attr("src", defaultimage);
if (image != '' && altdata != '') {
console.log("afeef");
$('.imagelazy').bind('error', function() {
$(this).attr("src", defaultimage);
});
$(".imagelazy img")
.error(function() {
$(this).hide();
})
.attr("src", defaultimage);
} else if (image == '' && altdata != '') {
$.each($('.imagelazy'), function(index, value) {
var alt1 = $(this).attr('alt').split("");
console.log(alt1);
if (alt1 != '') {
var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
}
console.log(this.outerHTML);
console.log(imagepath1);
$(this).attr("src", imagepath1);
});
} else if (altdata == '' && image == '') {
$.each($('.imagelazy'), function(index, value) {
$(this).attr("src", defaultimage);
console.log(this.outerHTML);
});
}
});
}
问题
- 向下滚动页面时脚本不起作用.
- 在src中设置图像并设置alt标签后,还会显示名字图像.
-
onerror
在js中不起作用. - 我在Google上搜索了很多内容,没有找到解决此问题的方法.
- 我发现了lazy.min.js js,它设置了src ="和data-src ="pathimage" 将解决此问题.
-
我们的要求是优化html,这就是为什么我通过js搜索替代解决方案的原因.
- Script is not working when scrolling down the page.
- When the image is set in src and alt tag is set then also first name image is displayed.
onerror
is not working in js.- i have googled a lot coudln"t found the solution for this issue.
- i have found lazy.min.js js which set src="" and data-src="pathimage" would handled this issue.
our requirement is optimize html that why im searching for alternate solution through js.
我找到了jquery链接: https://api.jquery.com/error/
i have found jquery link : https://api.jquery.com/error/
推荐答案
jQuery Ajax:
jQuery Ajax:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
JavaScript:
Javascript:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
图像检查:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
其他:
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
HTML:
<img src="image.gif" onerror="imgError()" />
function imgError()
{
alert('The image could not be loaded.');
}
这篇关于如何使用JavaScript检查图像URL为404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文