如何应用youtube嵌入代码(如果字符串是youtube url)

How to apply youtube embed code (If string is youtube url)

本文关键字:youtube 如果 字符串 url 代码 应用 何应用      更新时间:2024-01-03

我尝试应用youtube url中的嵌入代码,一切都很好。但我想找到解决方案,如果字符串不是youtube链接,那么就不要应用嵌入代码。

这是我的代码

$(document).ready(function() {
$('.youtube').html(function(i,v){
    var id = v.split('watch?v=')[1]; // get the id so you can add to iframe
    return '<iframe width="490" height="300" src="http://www.youtube.com/embed/' + id +"?wmode=opaque"+ '" frameborder="0" allowfullscreen></iframe>';
});
});

我真的不知道该怎么做?有人能帮我吗?

我会添加一个条件查找'watch?v=',然后再运行分割函数。

像这样:

$(document).ready(function() {
    $('.youtube').html(function(i,v){
        // check for an instance of 'watch?v='
        if (v.indexOf('watch?v=') !== -1) {
            var id = v.split('watch?v=')[1]; // get the id so you can add to iframe
            return '<iframe width="490" height="300" src="http://www.youtube.com/embed/' + id +"?wmode=opaque"+ '" frameborder="0" allowfullscreen></iframe>';
        } else {
            // return full url as string if not a youtube
            return v;
        }
    });
});

希望能有所帮助!