【问题标题】:Search for Text in Loaded HTML document在加载的 HTML 文档中搜索文本
【发布时间】:2017-09-27 20:37:30
【问题描述】:

我有一个网页,我的侧边栏链接会导致将“外部”HTML 文档加载到内容 div 中。
但是成功加载并显示后,加载的 HTML 内容并没有出现在 Page Source 中。
无论如何,我现在需要使用 Javascript 函数对该“外部”HTML 文档进行客户端文本搜索。

我的网页如下所示:

搜索文本框和按钮位于 Content Div 的“外部”(以红色为边框)。

并且,当链接的 HTML 文档之一出现在屏幕上时,页面源代码如下所示:

<!-- Page Content -->
<div id="page-content-wrapper" style="border: thick solid #FF0000; height:660px">
          <!--Loaded content goes here-->
</div>  

请注意,“已加载”的 HTML 文档未显示。

我找到了一个看起来很有希望的 Javascript 函数 findInPage(),但它没有找到“加载”的 HTML 文档及其文本。

// =====================================
function findInPage() {

    var str = document.getElementById("ButtonForm").elements["txtSearch"].value;
    var n = 0;
    var txt, i, found;
    if (str == "")
        return false;

    // Find next occurance of the given string on the page, wrap around to the
    // start of the page if necessary.
    if (window.find) {
        // Look for match starting at the current point. If not found, rewind
        // back to the first match.
        if (!window.find(str)) {
            while (window.find(str, false, true))
                n++;
        } else {
            n++;
        }
        // If not found in either direction, give message.
        if (n == 0)
            alert("Not found.");
    } else if (window.document.body.createTextRange) {

        txt = window.document.body.createTextRange();
        // Find the nth match from the top of the page.
        found = true;
        i = 0;
        while (found === true && i <= n) {

            found = txt.findText(str);
            if (found) {
                txt.moveStart("character", 1);
                txt.moveEnd("textedit");
            }
            i++;
        }
        // If found, mark it and scroll it into view.
        if (found) {
            txt.moveStart("character", -1);
            txt.findText(str);
            txt.select();
            txt.scrollIntoView();
            n++;
        } else {
            // Otherwise, start over at the top of the page and find first match.
            if (n > 0) {
                n = 0;
                findInPage(str);
            }
            // Not found anywhere, give message. else
            alert("Not found.");
        }
    }
    return false;
}

有没有办法修改函数和/或使用不同的函数,以便它可以找到“加载”的 HTML 文档并在其中搜索输入的文本?

【问题讨论】:

  • 您究竟是如何将文档加载到您的 div 中的?您使用 AJAX 或 iframe 还是 ...?
  • 我不使用 iframe。相反,我将 加载到具有 InnerHTML = 的 div 中

标签: javascript html


【解决方案1】:

尝试通过 id 选择 div 而不是读取整个窗口...

document.getElementById('page-content-wrapper').find(str)

【讨论】:

  • 感谢您的建议。我在Javascript函数中尝试了用“document.getElementById('page-content-wrapper').”替换“window.”的所有地方虽然脚本没有崩溃,但它仍然没有找到文本“生成”我正在寻找的内容。
【解决方案2】:

这是How to get html elements from an object tag? 的副本。

答案在于将window.document的所有实例替换为document.getElementById('page-content-wrapper').contentDocument,这样搜索到的文档就是页面文档。

但是,你那里的搜索功能很糟糕,它依赖于 window.find 来搜索窗口而不是搜索文档文本。

你可以建立一个更好的搜索功能:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Wrapper</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
    Body Here
    <object id="page-content-wrapper" type="text/html" data="about.html" name="content"></object>
        <input id="txtSearch" placeholder="Search..." />
        <button onclick="findInPage()">Search</button>
    <script>
        function findInPage() {
            var needle = document.getElementById('txtSearch').value;
            var haystack = document.getElementById('page-content-wrapper').contentDocument.body.innerHTML;
            var match = haystack.indexOf(needle);
            if(match != -1) {
                console.log(match);
            } else {
                console.log('Not Found');
            }
        }
    </script>
    </body>
</html>

用您想要加载和搜索的任何内容填写 about.html。

请注意,这只是记录匹配的索引。它不会将其滚动到视图中或选择它。多一点 javascript 你可以做到这些。你只需要通过 document.getElementById('page-content-wrapper').contentDocument.body

【讨论】:

  • 感谢您的建议。我试过了,但是当该行执行时,'haystack' 保持未定义 - 从而导致其余代码被忽略。
  • 在进一步调试时,似乎 .contentDocument.body 无效
  • 在进一步测试中我发现.... *** var Div = document.getElementById('page-content-wrapper'); *** var Obj = document.getElementById('page-content-wrapper').children[0]; *** var innerHTML = document.getElementById('page-content-wrapper').children[0].innerHTML; *** 但是即使文档在 Div 中显示在屏幕上,innerHTML = ""
【解决方案3】:

我终于找到了如何访问 Object 的 innerHTML 的 HTML 内容。
在单击特定的侧边栏链接后,我使用 Javascript 构建了它的对象。

function MenuClick(doc) {
var Tutorial = doc;
var DisplayObj = "<object id='ThisObj' type='text/html' data='" + Tutorial + "' style='min-width:100%; min-height: 101%; overflow: hidden'></object>";
        document.getElementById("page-content-wrapper").innerHTML = DisplayObj;
}  

但现在我已向对象('ThisObj')添加了一个 ID。

现在定义了该 ID,我能够“向下钻取”该对象以获取其内部 HTML。

var sourceObj = document.querySelector("#ThisObj");
var sourceBody = sourceObj.contentDocument.body
var haystack = sourceBody.innerHTML;

var match = haystack.indexOf(needle);
if (match != -1) {
  // --- Text match found ---
} else {
  // --- Text match NOT found ---
}  

我仍然需要创建 Javascript 以突出显示“找到”文本并将其滚动到视图中,但我将在单独的帖子中提出这个问题。

感谢您的建议/建议。

【讨论】:

  • 在进一步测试中这也不起作用。 sourceObj 已定义,但它没有定义“contentDocument”元素,因此没有“body”。我确实找到了 sourceObj.data 对象中定义的“外部”HTML,但没有找到。所以我仍然没有一个可行的解决方案。
猜你喜欢
  • 2015-08-23
  • 2011-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
相关资源
最近更新 更多