jQuery: Catching an image load event error 404, can it be done?

こ雲淡風輕ζ 提交于 2019-12-22 04:59:07

问题


I'm basically looping over a bunch of youtube video url's to get each video's id code.

I then reiterate over all 'thumbnail' images in a list and replace the source with the youtube video thumbnail url.

The problem I am currently running into is that if the video has been removed from youtube the resulting image source will not return a functioning image url, however the replace is still firing thus a broken image url is placed into the list.

How can I get jQuery to detect whether the url is actually still working before replacing the initial image source with the thumbnail source?

Here is my code that loops over the youtube clips on the page and filters their IDs:

function generateYoutubeThumbnails() {
    var YTT = {};
    YTT.videos = $('.video-thumbnail'); // the placeholder thumbnail image

    YTT.videos.each(function(i) {
        YTT.url = $(this).attr('data-videourl'); // the youtube full url, eg: http://www.youtube.com/watch?v=F52dx9Z0L5k
        YTT.videoId = YTT.url.replace(/(.+?)watch\?v=/gi,'').replace(/\&(.+)$/gi,''); // find and replace to get just the id: eg: F52dx9Z0L5k

        YTT.snip = 'http://img.youtube.com/vi/'+ YTT.videoId +'/hqdefault.jpg'; // the thumbnail url which would return: http://img.youtube.com/vi/F52dx9Z0L5k/hqdefault.jpg in this case.

        $(this).attr('src', YTT.snip); // replace the placeholder thumbnail with the proper youtube thumbnail that we got above
    });
}
generateYoutubeThumbnails();

Any ideas on how I can stop the find and replace of the last step if the resulting url is not working?


回答1:


jQuery

$('img').bind('error', function() {
   alert('image did not load');
});

jsFiddle.

Without jQuery

Array.forEach(document.getElementsByTagName('img'), function(img) {
    img.addEventListener('error', function() {
        this.style.border = '5px solid red';
    }, false);
});

jsFiddle.

The without jQuery example uses some methods not available in older IEs. You can shim these methods or use more compatible techniques.



来源:https://stackoverflow.com/questions/4361973/jquery-catching-an-image-load-event-error-404-can-it-be-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!