gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:36:24 25 4
gpt4 key购买 nike

我基本上是循环访问一堆 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();

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

最佳答案

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 中不可用的方法。您可以填充这些方法或使用更兼容的技术。

关于jQuery:捕获图像加载事件错误404,可以做到吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4361973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com