首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >jQuery:捕获图像加载事件错误404,可以这样做吗?

jQuery:捕获图像加载事件错误404,可以这样做吗?
EN

Stack Overflow用户
提问于 2010-12-06 07:28:47
回答 1查看 6K关注 0票数 7

我基本上是遍历了一堆youtube视频的url来获取每个视频的id代码。

然后我在一个列表中重复所有的‘缩略图’图片,并用youtube视频缩略图url替换源代码。

我目前遇到的问题是,如果视频已经从youtube上删除,那么生成的图像源将不会返回一个运行正常的图像url,但是替换仍然在触发,因此一个损坏的图像url会被放入列表中。

在用缩略图源替换初始图像源之前,如何让jQuery检测url是否仍然有效?

下面是我的代码,它循环遍历页面上的youtube剪辑并过滤它们的ID:

代码语言:javascript
复制
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();

有什么想法,我可以停止查找和替换最后一步,如果产生的网址不工作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-06 07:33:44

jQuery

代码语言:javascript
复制
$('img').bind('error', function() {
   alert('image did not load');
});

jsFiddle

不使用jQuery

代码语言:javascript
复制
Array.forEach(document.getElementsByTagName('img'), function(img) {
    img.addEventListener('error', function() {
        this.style.border = '5px solid red';
    }, false);
});

jsFiddle

不带jQuery的示例使用了一些在较早的IE中不可用的方法。您可以填补这些方法或使用更兼容的技术。

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4361973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档