Youtube URL 到 Iframe
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();
});
我是 运行 票务软件,能够操纵 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();
});