1

尝试编写用 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);
                    }
            }
        }
    }
4

1 回答 1

1

找到了解决方案!我将函数保存为外部文件,以便<head>在调用相应文章时附加到主 DOM 中,而不是嵌套在主 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);
    }
于 2012-11-26T23:33:08.283 回答