我基本上是循环播放一堆 YouTube 视频网址来获取每个视频id
code.
然后,我重申列表中的所有“缩略图”图像,并将源替换为 YouTube 视频缩略图 URL。
我当前遇到的问题是,如果视频已从 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();
如果生成的网址不起作用,有什么想法可以停止最后一步的查找和替换吗?
jQuery
$('img').bind('error', function() {
alert('image did not load');
});
jsFiddle http://jsfiddle.net/alexdickson/4B97T/1/.
没有 jQuery
Array.forEach(document.getElementsByTagName('img'), function(img) {
img.addEventListener('error', function() {
this.style.border = '5px solid red';
}, false);
});
jsFiddle http://jsfiddle.net/Rxqpm/.
The 没有 jQuery示例使用了一些旧 IE 中不可用的方法。你可以shim这些方法或使用更兼容的技术。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)