admin管理员组

文章数量:1415644

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.

本文标签: functionDetect 404 with javascriptStack Overflow