用iFrame替换所有对象标签 - 首次替换后停止 - Javascript

时间:2012-11-26 22:03:27

标签: javascript jquery windows-8 replacewith

尝试编写一个用iFrame替换所有YouTube对象标记的Javascript代码。相反,我写的函数将替换第一个<object>,然后在所述<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);
                    }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

找到解决方案!我将该函数保存为外部文件,每当调用相应的文章时,该文件将附加到主DOM中的<head>,而不是嵌套在主Javascript文件中。

function itemInvoked(e) {
        var currentArticle = articlesList.getAt(e.detail.itemIndex);
        WinJS.Utilities.setInnerHTMLUnsafe(articlecontent, currentArticle.content);
        var videoScript = document.createElement("script");
        videoScript.type = "text/javascript";
        videoScript.src = "/js/videoEditScript.js"
        document.getElementsByTagName("head")[0].appendChild(videoScript);
        articlelist.style.display = "none";
        articlecontent.style.display = "";
        mainTitle.innerHTML = currentArticle.title; 
        WinJS.UI.Animation.enterPage(articlecontent);
    }