function - Detect 404 with javascript - Stack Overflow

I'm currently using this JavaScript function to load an image into a div.function loadImage(id) {v

I'm currently using this JavaScript function to load an image into a div.

function loadImage(id) {
    var image = document.getElementById("image");
    image.src = "/"+id+".png";
    var image = document.getElementById("image");
    image.onload = function () {
            // Do stuff
    };
}

However, how can I do something if the image URL throws back a 404 error?

I'm currently using this JavaScript function to load an image into a div.

function loadImage(id) {
    var image = document.getElementById("image");
    image.src = "http://test./"+id+".png";
    var image = document.getElementById("image");
    image.onload = function () {
            // Do stuff
    };
}

However, how can I do something if the image URL throws back a 404 error?

Share Improve this question asked Dec 25, 2013 at 16:26 user2898075user2898075 791 gold badge3 silver badges10 bronze badges 1
  • Possible duplicate. See stackoverflow./questions/3019077/… and stackoverflow./questions/92720/… – Garett Commented Dec 25, 2013 at 16:38
Add a ment  | 

1 Answer 1

Reset to default 4

You can use onerror.

I am not sure if it reacts also on images as a 404 page, or on bad images only. In both cases, it will likely do what you need.

Alternatively, you can try using AJAX (e.g. XMLHttpRequest or its abstraction), which allows you to handle error codes. Cross-origin restrictions will apply, though. It may be also an overkill.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745240032a4618126.html

相关推荐

  • function - Detect 404 with javascript - Stack Overflow

    I'm currently using this JavaScript function to load an image into a div.function loadImage(id) {v

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信