如何使用javascript检查图像是否存在?

时间:2016-03-01 19:52:13

标签: javascript jquery

我的Javascript代码是这样的:

var json = {
        "Hotel": [{
                "ImageUrl": "http://us.dotwconnect.com/poze_hotel/110802-img1-1.jpg"
            }, {
                "ImageUrl": "http://www.google.com/images/srpr/nav_logo14.png"
            }]
    };

    var totalHotel = json.Hotel.length;

    var image = '';
    for(var i=0;i<totalHotel;i++){

        hotelImage = json.Hotel[i].ImageUrl;



        // The "callback" argument is called with either true or false
        // depending on whether the image at "url" exists or not.
        function imageExists(url, callback) {
            var img = new Image();
            img.onload = function() { callback(true); };
            img.onerror = function() { callback(false); };
            img.src = url;
        }

        // Sample usage
        var imageUrl = hotelImage;
        imageExists(imageUrl, function(exists) {
            // console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
             if(!exists){
                console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
                hotelImage = 'https://az853139.vo.msecnd.net/static/images/not-found.png';
            }

        });

        image += '<img style="width:180px; height:120px; margin:9px;" src="'+hotelImage+'" />';


    }
    // console.log(image);
    $('#image').html(image);

演示和完整代码如下:https://jsfiddle.net/oscar11/9omo18yn/

如何使用javascript检查是否存在未找到的图像?

我尝试这样,但它没有用。图像&#34;未找到&#34;没有出现

解决我问题的任何解决方案?

非常感谢

0 个答案:

没有答案