jQuery/JavaScript to replace broken images

后端 未结 30 2507
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  既然无缘
    2020-11-21 06:19

    Pure JS. My task was: if image 'bl-once.png' is empty -> insert the first one (that hasn't 404 status) image from array list (in current dir):

    Maybe it needs to be improved, but:

    var srcToInsertArr = ['empty1.png', 'empty2.png', 'needed.png', 'notActual.png']; // try to insert one by one img from this array
        var path;
        var imgNotFounded = true; // to mark when success
    
        var replaceEmptyImage = {
            insertImg: function (elem) {
    
                if (srcToInsertArr.length == 0) { // if there are no more src to try return
                    return "no-image.png";
                }
                if(!/undefined/.test(elem.src)) { // remember path
                    path = elem.src.split("/").slice(0, -1).join("/"); // "http://localhost:63342/GetImage"
                }
                var url = path + "/" + srcToInsertArr[0];
    
                srcToInsertArr.splice(0, 1); // tried 1 src
    
                
                    if(imgNotFounded){ // while not success
                        replaceEmptyImage.getImg(url, path, elem); // CALL GET IMAGE
                    }
                
    
            },
            getImg: function (src, path, elem) { // GET IMAGE
    
                if (src && path && elem) { // src = "http://localhost:63342/GetImage/needed.png"
                    
                    var pathArr = src.split("/"); // ["http:", "", "localhost:63342", "GetImage", "needed.png"]
                    var name = pathArr[pathArr.length - 1]; // "needed.png"
    
                    xhr = new XMLHttpRequest();
                    xhr.open('GET', src, true);
                    xhr.send();
    
                    xhr.onreadystatechange = function () {
    
                        if (xhr.status == 200) {
                            elem.src = src; // insert correct src
                            imgNotFounded = false; // mark success
                        }
                        else {
                            console.log(name + " doesn't exist!");
                            elem.onerror();
                        }
    
                    }
                }
            }
    
        };

    So, it will insert correct 'needed.png' to my src or 'no-image.png' from current dir.

提交回复
热议问题