简体   繁体   English

捕获页面加载后创建的<img>标记的img加载错误(例如,通过AJAX)

[英]Catching img load error for <img> tags created after page load (e.g. via AJAX)

I'm using jQuery's error event handler to catch image loading errors. 我正在使用jQuery的error事件处理程序来捕获图像加载错误。 It looks like this: 它看起来像这样:

$(function(){
  $('img').error(function(){
    // ... do something
  })
})

This works great for images that are in the DOM when the page is loaded. 这对于加载页面时DOM中的图像非常有用。 However, I'd like to catch the errors for <img> tags that get inserted via AJAX, too. 但是,我想捕获通过AJAX插入的<img>标签的错误。 I'd prefer to not have to run certain code after every AJAX call. 我希望在每次调用AJAX之后都不必运行某些代码。

I'd like something like this, although this doesn't seem to work: 我喜欢这样的东西,虽然这似乎不起作用:

$('body').on('error', 'img', function(){
  // ... do something
})

If you don't want to set the binding after every ajax call, you might want to set it in a global ajax complete function 如果您不想在每次ajax调用后设置绑定,您可能希望在全局ajax完成函数中设置它

//Gloabal Ajax Complete
$("body").bind("ajaxSend", function(e, xhr, settings){
   //Sent
}).bind("ajaxComplete", function(e, xhr, settings){
   //Complete
   $('img').error(function(){
       // ... do something
   })
}).bind("ajaxError", function(e, xhr, settings, thrownError){
    //Error
});

You can use jQuery's live() or delegate() or on() methods depending on jQuery version you're using to register the error event on current and future image elements you add to the document. 您可以使用jQuery的live()或delegate()或on()方法,具体取决于您用于在添加到文档的当前和未来图像元素上注册错误事件的jQuery版本。 Refer http://api.jquery.com/live/ 请参阅http://api.jquery.com/live/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM