我基本上是遍历了一堆youtube视频的url来获取每个视频的id代码。
然后我在一个列表中重复所有的‘缩略图’图片,并用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();有什么想法,我可以停止查找和替换最后一步,如果产生的网址不工作?
发布于 2010-12-06 07:33:44
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中不可用的方法。您可以填补这些方法或使用更兼容的技术。
https://stackoverflow.com/questions/4361973
复制相似问题