如何从图片缩略图源获取YouTube视频ID,并设置为iframe? [英] how to get YouTube video id from image thumbnail source, and set as an iframe?

查看:159
本文介绍了如何从图片缩略图源获取YouTube视频ID,并设置为iframe?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果图片代码是

<img src="http://i1.ytimg.com/vi/LL0Y4MZ45bo/0.jpg" class="youtubeimg"></img>

我不知道如何提取YouTube视频ID( LL0Y4MZ45bo <缩进图像src中的/ code>)然后将其应用到iframe。

I don't know how to extract the YouTube video id (LL0Y4MZ45bo) from the thumbnail image src and then apply it to an iframe.

目前我有100%工作,它将src应用于iframe。但我不知道怎么做是从这个案例中的img标签获取id LL0Y4MZ45bo 并将其添加到youtube embed src http://www.youtube.com/embed/ LL0Y4MZ45bo

currently i have 100% working, which applys the src to the iframe. but what i dont know how to do is get the id from the img tags in this case LL0Y4MZ45bo and add it to the youtube embed src http://www.youtube.com/embed/LL0Y4MZ45bo

<iframe src="" class="youtubeiframe"></iframe>

<script>
$(".youtubeiframe").attr({ 
  src: "http://www.youtube.com/embed/VIDEO-ID-EXTRACTED-FROM-THUMBNAIL-SRC",
});
</script>

那么如何从img中提取id并应用于iframe src?

so how can I extract id from the img and apply to iframe src?

推荐答案

这提取使用正则表达式的YouTube ID ,我假设它至少有11个字符作为第一个YouTube视频ID 有11个。

This extracts the YouTube ID using a Regular Expression, I made the assumption that it would be a minimum of eleven characters as the first YouTube Video ID has 11.

<img src="http://i1.ytimg.com/vi/LL0Y4MZ45bo/0.jpg" class="youtubeimg"></img>
<iframe src="" class="youtubeiframe"></iframe>

<script>
    $(function (){
        var youtubeid = $(".youtubeimg").attr("src").match(/[\w\-]{11,}/)[0];
        $(".youtubeiframe").attr({ 
              src: "http://www.youtube.com/embed/" + youtubeid,
        });
    });
</script>

这是有效的,但 YouTube播放器API 可以为您提供更稳定的加载iFrame的解决方案,将来一旦稳定我会推荐 YouTube iFrame API

This works, however the YouTube Player API may provide you with a more stable solution to loading that iFrame, in the future once it becomes stable I would recommend the YouTube iFrame API

这篇关于如何从图片缩略图源获取YouTube视频ID,并设置为iframe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆