jquery replace YouTube iFrame

2019-04-12 14:08发布

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条回答
Emotional °昔
2楼-- · 2019-04-12 14:42
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/

查看更多
登录 后发表回答