作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我基本上是循环访问一堆 YouTube 视频网址来获取每个视频的 id
代码。
然后,我会重申列表中的所有“缩略图”图像,并将源替换为 YouTube 视频缩略图网址。
我当前遇到的问题是,如果视频已从 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://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();
如果生成的网址不起作用,有什么想法可以停止最后一步的查找和替换吗?
最佳答案
$('img').bind('error', function() {
alert('image did not load');
});
jsFiddle .
Array.forEach(document.getElementsByTagName('img'), function(img) {
img.addEventListener('error', function() {
this.style.border = '5px solid red';
}, false);
});
jsFiddle .
没有 jQuery 示例使用了一些旧版 IE 中不可用的方法。您可以填充这些方法或使用更兼容的技术。
关于jQuery:捕获图像加载事件错误404,可以做到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4361973/
我是一名优秀的程序员,十分优秀!