简体   繁体   English

使用handlebars.js时无法检测到IMG jQuery错误事件。 如何修复这些损坏的图像?

[英]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.

相关问题 如何使用 JS/JQuery 检测视频是否全屏? - How can I detect if a video is full screen using JS/JQuery? 如何使用播放器JavaScript检测到断开的视频链接? - How can I detect a broken video link using player JavaScript? 我如何使用 partial 将 append js 转换为 express handlebars 模板? - How I can append js into a express handlebars template using partial? 如何使用javascript / JQuery在所有dom图像上交换img src中的一个术语? - How can i swap one term in img src on all dom images using javascript / JQuery? 我如何解决这个jQuery故障,以便在使用.hover()时div不会消失? - How can I fix this jQuery glitch so the div doesn't try to disappear when using .hover()? 当我将它与Jquery.smoothState.js组合时,BXslider.js被破坏了。 我该如何解决? - BXslider.js is broken when I combine it with Jquery.smoothState.js. How do I fix this? 无法获取 img 的 src(JS,Jquery) - Can't get src of img (JS, Jquery) 如何使用Selenium IDE测试损坏的图像? - How can I test broken images using Selenium IDE? 我如何使用 Jquery 检测输入值何时发生变化 - How i can detect when input values are change using Jquery Javascript / JQuery-如何为损坏的图像重置onError函数? (对于第二个损坏的图像) - Javascript/JQuery - How can I reset onError function for broken images? (for a second broken image)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM