how to get YouTube video id from image thumbnail source, and set as an iframe?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-29 09:53:46

问题


So if the image tag is

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

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

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>

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


回答1:


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>

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




回答2:


I think you can do this more easily if you'll start to study the YouTube API.




回答3:


Make the URL as an array and than take the second to last part. For example this also works with CSS background-image.

id = $('div').attr('style').split('/');
id = id[id.length-2];
alert("YouTube ID: " + id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-image:url('https://img.youtube.com/vi/MHUOty8-Ty0/0.jpg');"></div>

https://jsfiddle.net/Wobbo/wfyL1hem/7/



来源:https://stackoverflow.com/questions/7870113/how-to-get-youtube-video-id-from-image-thumbnail-source-and-set-as-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!