如果背景图像URL为404,则jQuery



我正在使用以下代码将背景图像缩略图作为嵌入式YouTube视频的占位符。如果视频被删除,则缩略图将变为YouTube的默认404缩略图。我想设置自己的404缩略图,但我不确定如何。我可以找到检查IMG错误的方法,但不能发现背景图像错误。(另外,我不能寻找没有背景图像的divs,因为它们都会有一个,这可能只是一个断开的链接。)

有人知道如何检查损坏的背景图像网址?

$(function(){ 
    // VIDEO LOAD
        var videoLinks = {};
        function clickVideo() {
            // trim off img-
            var postId = $(this).attr("id").substr(4);
            if (videoLinks[postId]) {
                $("#" + postId).html(videoLinks[postId]);
            }
        }
        function storeVideo() {
            var videoDiv = this;
            var postId = $(videoDiv).attr("id");
            var code = $(videoDiv).attr("videohtml");
            $(videoDiv).removeClass("videoNoThumbnail");
            var re = new RegExp("(.*/embed/([a-zA-Z0-9_-]+)\?)(.*)", "m");
            var match = code.match(re);
            if (match) {
                code = match[1] + "autoplay=1&" + match[3];
                var videoId = match[2];
                var div = $("<div class=videoThumbnail />");
                div.css("background-image",
"url('http://img.youtube.com/vi/" + videoId + "/0.jpg')");

                var img = $("<img src=http://dinakelberman.com/play.png class=playButton />");
                img.attr("id", "img-" + postId);
                img.click(clickVideo);
                div.append(img);
//                two.empty();
                $(videoDiv).append(div);
            }
            videoLinks[postId] = code;
        }
        function updateVideos() {
            $('div.videoNoThumbnail').each(storeVideo);
            setTimeout(updateVideos, 200);
        }
        updateVideos();
})

这可以通过使用Ajax请求加载缩略图图像来完成:当YouTube服务404缩略图时,它实际上以404状态响应。

$.get('http://img.youtube.com/vi/' + videoId + '/0.jpg')
.success(function(d){
    // video not removed: set thumbnail
    div.css("background-image","url('http://img.youtube.com/vi/" + videoId + "/0.jpg')");   
})
.error(function(d){
    // video removed: set your own thumbnail
});

可以进一步调整成功的情况:我编写的代码两次加载相同的图像(首先使用Ajax请求,然后在设置背景图像时)。实际上,您可以使用带有AJAX请求的图像,将响应数据转换为Data-uri图像背景。

为此,您需要使用二进制传输来请求图像(或使用标准xmlhttprequest进行),然后将数据转换为base64。

最新更新