jquery replace YouTube iFrame

主宰稳场 提交于 2020-01-01 18:41:07

问题


If a YouTube iframe embed code is ...

<iframe width="560" height="315" src="http://www.youtube.com/embed/dd8W4PNUU3Q?rel=0" frameborder="0" allowfullscreen></iframe>

how can you extract dd8W4PNUU3Q ie, the video id

and replace the entire iframe with

<img style="background-image:url('http://i1.ytimg.com/vi/dd8W4PNUU3Q/hqdefault.jpg');" class="someClass"/>

and wrap the image with a <a> giving...

<a href="http://www.MYURL.com/?v=dd8W4PNUU3Q"><img style="background-image:url('http://i1.ytimg.com/vi/dd8W4PNUU3Q/hqdefault.jpg');" class="someClass"/></a>

回答1:


var RE = /embed\/([a-zA-Z0-9_-]{11})/;

jQuery( "iframe" ).each(function(){

var id = ( this.src.match( RE ) || [] )[1];

    if( id ) {
    jQuery( this ).replaceWith( '<a href="http://www.MYURL.com/?v='+id+'">'+
                                '<img src="http://i1.ytimg.com/vi/'+id+'/hqdefault.jpg"'+
                                ' class="someClass" /></a>' );
    }

});

Jsfiddle: http://jsfiddle.net/4E3DH/1/



来源:https://stackoverflow.com/questions/8203956/jquery-replace-youtube-iframe

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