javascript - 如何用 javascript 代码中的嵌入代码替换 youtube/vimeo url?

标签 javascript jquery html youtube vimeo

我尝试用 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 修改为正确的代码?

最佳答案

在示例 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>')
        );    
    })

它现在应该可以工作了。

关于javascript - 如何用 javascript 代码中的嵌入代码替换 youtube/vimeo url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20915664/

相关文章:

jQuery 使用两个按钮在三种不同样式之间更改单个 div 的类

javascript - jQuery 滚动事件每次滚动触发一次

javascript - Jquery可拖动图像拖放到左上角所在的div

javascript - 在维护数据的同时链接 promise (angular js)

javascript - 将 Highcharts StockChart 范围选择器的大小调整为少于 6 个数据点

javascript - 使用 jQuery 限制文本区域中的行数和显示行数

php - MySQL数据库实时更新网页

python - 如何从 Bing/Google news feed 解析并获取干净的图像源?

html - 我应该如何居中对齐 html 表单?

javascript - 添加溢出隐藏到主体