【问题标题】:How can I replace youtube / vimeo url with embed code in javascript code?如何将 youtube / vimeo url 替换为 javascript 代码中的嵌入代码?
【发布时间】:2014-01-21 19:58:14
【问题描述】:

我尝试用 javascript 代码中的嵌入代码替换 youtube 和 vimeo url。

我用过这段代码:

示例 1:

HTML:

<div id="divContent"></div>

JAVASCRIPT:

$("#divContent").html('http://www.youtube.com/watch?v=t-ZRX8984sc <br /> http://vimeo.com/82495711 <br /> http://youtu.be/t-ZRX8984sc');

$('#divContent').html(function(i, html) {
    return html.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="200" height="100" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe src="//player.vimeo.com/video/$1" width="200" height="100" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');

});

演示示例 1: http://jsfiddle.net/88Ms2/301/ - 它不起作用。

示例 2

HTML:

<div id="divContent">
http://www.youtube.com/watch?v=t-ZRX8984sc
    <br />
http://vimeo.com/82495711
    <br />
http://youtu.be/t-ZRX8984sc
</div>

JAVASCRIPT:

$('#divContent').html(function(i, html) {
    return html.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="200" height="100" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe src="//player.vimeo.com/video/$1" width="200" height="100" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');

});

演示示例 2: http://jsfiddle.net/88Ms2/300/ - 工作正常

我已经使用 ajax 从数据库中检索了数据。我需要使用 javascript 将带有 html 代码的数据插入到 div 中。如何将示例 1 修改为正确的代码?

【问题讨论】:

    标签: javascript jquery html youtube vimeo


    【解决方案1】:

    在示例 1 中,将 javascript 代码更改为:

    $('#divContent').contents()
        .filter(function(){
            return this.nodeType === 3;
         })
        .map(function(index, text){
            $(text).replaceWith(
                text.textContent.replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe width="200" height="100" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe src="//player.vimeo.com/video/$1" width="200" height="100" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>')
            );    
        })
    

    它现在应该可以工作了。

    【讨论】:

    • 您可以查找除空格以外的任何内容,因为在 url 之后可能会有更多文本,可以这样做: ([^\ ]+) 而不是 (.+) 这是一个示例:jsfiddle.net/w5grvL5q
    猜你喜欢
    • 2015-03-02
    • 2012-01-02
    • 2013-03-27
    • 2012-08-03
    • 2010-12-22
    • 2011-03-15
    • 2012-11-14
    • 2012-01-22
    • 2013-11-10
    相关资源
    最近更新 更多