使用jQuery修改样式时可以捕获HTTP错误吗? [英] Can I catch http errors when using jQuery to modify styles?

查看:116
本文介绍了使用jQuery修改样式时可以捕获HTTP错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用jQuery这样设置页面的背景图像:

If I use jQuery to set the background image of the page like so:

$('body').css({
    "background-image": 'url(' + myImageUrl + ')'
});

如何检测图像URL可能返回的HTTP错误(500、503、404等)?

How can I detect and handle HTTP errors (500, 503, 404, etc) that might be returned from the image URL?

我确实找到了一个注册回调的jQuery .error()方法,但是在1.8中已将其标记为已弃用,但没有表明应该用什么代替它. (无论是否赞成,我似乎也无法使其正常工作.)

I did find a jQuery .error() method that registers a callback, but it's marked as deprecated in 1.8 with no indication of what is supposed to replace it. (I also can't seem to get it to work, deprecated or not.)

根据下面的评论和答案,我尝试了这种变体,它似乎奏效了,但答案越来越不赞成.有什么不好的理由吗?

Based on the comments and the answer below I tried this variation and it seems to work, but the answer is getting down-votes. Is there a reason this is bad?

$('<img>').error(function(obj) {
    alert('error');
}).load(function() {
    $('body').css({
        "background-image": 'url(' + myImageUrl + ')'
    });
}).attr('src', myImageUrl);

推荐答案

尝试一下

jQuery

实时演示

var $image = $("<img />");
$image.on("error",function() { 
  $('body').css({
    "background-image": 'url(defaultimage.jpg)'
  });
}).on("load",function() {
  $('body').css({
    "background-image": 'url(' + myImageUrl + ')'
  });
}).attr("src",myImageUrl);

JavaScript:

JavaScript:

var image = new Image();
image.onerror=function() { 
  document.body.style.backgroundImage="url(defaultimage.jpg)"
}
image.onload=function() {
  document.body.style.backgroundImage="url("+myImageUrl+")"
}
image.src=myImageUrl;

这篇关于使用jQuery修改样式时可以捕获HTTP错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆