用例:
- 当 src 不为空且 alt 标签不为空时显示 src 的图像。
- 然后检查 src 图片 url 不是 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 中不工作。- 我在谷歌上搜索了很多都没有找到解决这个问题的方法。
- 我找到了设置 src=""和 data-src="pathimage"的 lazy.min.js js 会处理这个问题。
我们的要求是优化 html,所以我通过 js 寻找替代解决方案。
我找到了 jquery 链接:https://api.jquery.com/error/
最佳答案
jQuery Ajax :
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
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 - 如何使用javascript检查图像url是否为404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31936444/