afe*_*eef 4 html javascript jquery image
使用案例:
HTML:
<img class="imagelazy" id="lazyimage" src="http://url" alt="ankit">
Run Code Online (Sandbox Code Playgroud)
使用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);
});
}
});
}
Run Code Online (Sandbox Code Playgroud)
问题
onerror 是不是在js工作.我们的要求是优化HTML,为什么我通过js搜索替代解决方案.
我找到了jquery链接:https://api.jquery.com/error/
Aru*_*mar 10
jQuery Ajax:
$.ajax({
url:'http://www.example.com/somefile.ext',
type:'HEAD',
error: function()
{
//file not exists
},
success: function()
{
//file exists
}
});
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
Run Code Online (Sandbox Code Playgroud)
图像检查:
function ImageExist(url)
{
var img = new Image();
img.src = url;
return img.height != 0;
}
Run Code Online (Sandbox Code Playgroud)
其他:
$.get(url)
.done(function() {
// exists code
}).fail(function() {
// not exists code
})
Run Code Online (Sandbox Code Playgroud)
HTML:
<img src="image.gif" onerror="imgError()" />
function imgError()
{
alert('The image could not be loaded.');
}
Run Code Online (Sandbox Code Playgroud)
这个选择器是不是错了:
$(".imagelazy img")
Run Code Online (Sandbox Code Playgroud)
这应该是:
$("img.imagelazy")
Run Code Online (Sandbox Code Playgroud)
或者只是图像类名称:
$(".imagelazy")
Run Code Online (Sandbox Code Playgroud)
而且您不必将文档就绪块包装在任何功能块中。您可以优化您的代码,例如:
$('.imagelazy').attr('src', function() {
var alt1 = $(this).attr('alt').split("");
if (alt1 != '') {
var imagepath1 = "http://im.gifbt.com/userimages/" + alt1[0].toLowerCase() + ".jpg";
}
return imagepath1;
});
Run Code Online (Sandbox Code Playgroud)