[英]Can't detect IMG jquery error event when using handlebars.js. How can I fix these broken images?
I'm having trouble detecting the error event of an image with a broken source. 我无法检测到源损坏的图像的错误事件。
The image is created in handlebars like this: 图像是在这样的车把中创建的:
<img src="{{image}}" alt="the image">
I'm trying this code: 我正在尝试以下代码:
console.log('first log');
$('img').one('error', function() {
console.log('image error detected');
this.src = "<my other image path here>";
});
I can't get my console.log, unless I hit "back" and then "forward" in the chrome browser navigation bar. 我无法获得console.log,除非在Chrome浏览器的导航栏中单击“后退”然后“前进”。 The replacement of 'this.src' also works if I hit "back" and then "forward".
如果我先按“后退”再按“前进”,则替换“ this.src”也可以。
I've tried many things like .load or putting this code in document ready, etc. 我已经尝试了很多事情,例如.load或将此代码放在文档中等。
When I view the console, I see the two GET's for the two images on this page, followed by the "first log" above. 当查看控制台时,我在此页面上看到两个图像的两个GET,后面是上面的“第一个日志”。 So, the images are hitting the error event well before my listener has been binded.
因此,在绑定我的侦听器之前,图像碰到了错误事件。 Or something like that maybe...
或类似的东西...
Any suggestions? 有什么建议么?
Finally got this working. 终于成功了。 I'm sure there is a better way, but this is what did it for me:
我敢肯定有更好的方法,但这就是为我做的:
if ($('[data-path="/blahblah"]').length) {
$('.myClass img').each(function() {
var image = $(this);
if (image.context.naturalWidth == 0 || image.readyState == 'uninitialized') {
image.unbind('error').attr("src", "<placeholder src here>");
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.