html - Web 浏览器如何实现文本搜索?

标签 html dom browser full-text-search

我想构建一个包含 HTML Web 控件的应用程序,并能够在 html 区域中搜索和突出显示多个短语,就像今天在 Web 浏览器中实现的那样。 主要思想是让搜索忽略 html 特殊标签,只引用真实文本(内部 html)。 我知道解决方案将包括编辑 DOM,但我不确定如何实现。 我在网上搜索了很多,我也看了Zavael的帖子,但不幸的是我找不到任何合适的答案。任何答案、示例或指导将不胜感激。

最佳答案

如果您指的是页面内 HTML 内容的内联搜索:首先我会说这可能不是一个好主意。您不应该取代浏览器的 native 功能。让用户按照他们习惯的方式做事。在不同的网站上保持一致的体验。

但是,如果您出于某些小众目的需要它,我认为这不会那么难。

jQuery 可以实现它。只是一个非常粗糙的开始:

//As you type in the search box...
$("#search_box").change(function() {
    //...you search the searchable area (maybe use some regex here)
    $("#search_area").html();
});

编辑:发问者问我是否可以详细说明代码。

//As you type in the search box...
$("#search_box").change(function() {
    //This part of the code is called when the contents of the search box changes

    //This is the contents of the searchable area:
    $("#search_area").html();

    //This is the contents of the search box:
    $(this).val();

    //So you could perform a function here, like replacing the occurences of the
    //search text with a span (you could use CSS to highlight the span with a
    //background colour:

    var html_contents = $("#search_area").html();
    var search_tem = $(this).val();

    $("#search_area").html(html_contents.replace(search_term, '<span class="highlight">'+search_term+'</span>'));
});

请注意,在上面的示例中,Javascript 的“替换”功能只会替换第一次出现的位置。您需要在第一个参数中使用正则表达式来替换所有。但我不想为您编写所有代码;)

关于html - Web 浏览器如何实现文本搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5433372/

相关文章:

Javascript:为什么我不能在 mac 上的浏览​​器中访问 '../..' 目录

html - 我的网站的响应式布局遇到问题

html - "infamous"CSS : 2 divs side-by-side, 跨浏览器版本(?)

javascript - Jquery:+ 不能正常工作

javascript - 每个父节点链都会终止吗?

React float-left 中的 Html 不起作用

javascript - 保护网络应用程序免受信息泄露

javascript - 如何使用 Javascript 将 HTML 属性添加到数组

html - 水平 div img 对齐

javascript - 如何在不将文本字符串插入 DOM 的情况下对文本字符串执行 document.querySelectorAll