【发布时间】:2015-11-03 08:44:32
【问题描述】:
用例:
- 当 src 不为 null 且 alt 标签不为 null 时显示 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/
【问题讨论】:
-
$(".imagelazy img")似乎不对。不应该是$("img.imagelazy")吗?此外,您似乎应该在主循环中迭代一次$.each($('.imagelazy')并在那个阶段读取image、altdata等 -
@afeef 你可能有其他问题,因为 onerror 总是可以正常工作
-
onerror 无法正常工作
标签: javascript jquery html image