jQuery:捕获图像加载事件错误404,可以这样做吗?
我基本上循环了一堆youtubevideourl来获取每个video的id
代码。
然后我重复列表中的所有“缩略图”图像,并用youtubevideo缩略图url替换源代码。
我目前遇到的问题是,如果video已从youtube中删除,则生成的图像源将不会返回正常运行的图像URL,但是替换仍然会触发,因此将损坏的图像URL放入列表中。
在使用缩略图源替换初始图像源之前,如何让jQuery检测url是否仍然有效?
这是我的代码循环遍历页面上的youtube剪辑并过滤其ID:
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://sofzh.miximages.com/jquery/hqdefault.jpg in this case. $(this).attr('src', YTT.snip); // replace the placeholder thumbnail with the proper youtube thumbnail that we got above }); } generateYoutubeThumbnails();
如果结果url不起作用,我怎么能停止查找和替换最后一步?
jQuery的
$('img').bind('error', function() { alert('image did not load'); });
jsFiddle 。
没有jQuery
Array.forEach(document.getElementsByTagName('img'), function(img) { img.addEventListener('error', function() { this.style.border = '5px solid red'; }, false); });
jsFiddle 。
没有jQuery示例使用旧IE中不可用的一些方法。 您可以填充这些方法或使用更兼容的技术。