尝试编写用 iFrame 替换所有 YouTube 对象标签的 Javascript 代码。相反,我编写的函数将替换 first <object>
,然后停止并丢弃之后的所有内容 said <object>
。
如果我使用不同的元素,例如换行符<br>
,它将成功替换所有<object>
标签,<br>
并且不会丢失任何内容。
function editVideoObjects(htmlContent) {
// Index all the objects and add ID tags
var objectTags = htmlContent.querySelectorAll("object");
var numberOfObjects = objectTags.length;
for (var r = 0; r < numberOfObjects; r += 1) {
objectTags[r].setAttribute("id", "video" + r)
}
for (var j = 0; j < numberOfObjects; j += 1) {
var currentObject = htmlContent.getElementById("video" + j);
var videoEmbed = currentObject.querySelector("embed");
if (videoEmbed != null) {
var videoSrc = videoEmbed.getAttribute("src");
//Script specific for YouTube videos.
if (videoSrc.split(".")[1] == "youtube") {
var newSrc = videoSrc.replace("/v/", "/embed/");
var iFrame = document.createElement("iframe");
iFrame.setAttribute("src", newSrc);
iFrame.setAttribute("height", currentObject.getAttribute("height"));
iFrame.setAttribute("width", currentObject.getAttribute("width"));
iFrame.setAttribute("frameborder", "0");
iFrame.setAttribute("allowfullscreen");
iFrame.setAttribute("id", "iFrameVideo" + j);
$(currentObject, htmlContent).replaceWith(iFrame);
}
}
}
}