Youtube URL to Iframe



我运行票务软件与操作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页面时,它会在其周围包装<P></P>标记。这会引起问题吗?

标签的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();
});