如何从图片缩略图源获取YouTube视频ID,并设置为iframe?

如何从图片缩略图源获取YouTube视频ID,并设置为iframe?

问题描述:

因此,如果图片代码是

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

我不知道如何提取YouTube视频ID( LL0Y4MZ45bo )然后将其应用到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