【问题标题】:Youtube URL to Iframe指向 iframe 的 Youtube 网址
【发布时间】:2015-07-13 18:37:10
【问题描述】:

我正在运行能够操纵 CSS 和 JS 进行自定义的票务软件,我需要将视频 URL 转换为 iframe。我目前正在使用此代码:

 $('#wiki-page-content').contents().each(function() {
// Skip non text nodes.
if (this.nodeType !== 3) {
    return true;
}
// Grab text
var matches = this.data.match(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g);

if (!matches) {
    return true;
}
var iframe = $('<iframe width="420" height="345" frameborder="0" allowfullscreen />', {
    src: 'http://www.youtube.com/embed/' + matches[1]
});
iframe.insertAfter(this);
$(this).remove();});

现在,问题是当有人使用文本编辑器将 URL 放入 WIKI 页面时,它会在其周围包裹一个 &lt;P&gt;&lt;/P&gt; 标记。这会导致问题吗?我该如何克服这个问题。

【问题讨论】:

    标签: javascript html css iframe youtube


    【解决方案1】:

    标签的noteType等于1。试试这样的:

    $('#wiki-page-content').contents().each(function() {
        // Skip non text nodes.
        var text;
    
        switch (this.nodeType) {
            case 3:
                text = this.data;
                break;
            case 1:
                text = this.innerHTML; // or this.textContent
                break;
            default:
                return true;
        }
    
        // Grab text
        var matches = text.match(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g);
    
        if (!matches) {
            return true;
        }
        var iframe = $('<iframe width="420" height="345" frameborder="0" allowfullscreen />', {
            src: 'http://www.youtube.com/embed/' + matches[1]
        });
        iframe.insertAfter(this);
        $(this).remove();
    });
    

    【讨论】:

    • 没有用,它使该类中的所有内容都消失了
    猜你喜欢
    • 1970-01-01
    • 2012-04-17
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多