HTML中的全文搜索忽略标签/&

Bru*_*uno 15 html javascript tags full-text-search highlighting

我最近看到很多用于在HTML页面中搜索和突出显示术语的库.但是,我看到的每个库都有同样的问题,他们找不到部分包含在html标签中的文本和/或他们找不到&-expressed的特殊字符.


示例a:

<span> This is a test. This is a <b>test</b> too</span>
Run Code Online (Sandbox Code Playgroud)

搜索"测试"会找到第一个但不是第二个.


例b:

<span> Pencils in spanish are called l&aacute;pices</span>
Run Code Online (Sandbox Code Playgroud)

搜索"lápices"或"lapices"将无法产生结果.


有没有一个JS库可以做到这一点,或者至少是一种规避这些障碍的方法?

提前致谢!

布鲁诺

Tim*_*own 35

您可以使用window.find()非IE浏览器和TextRangefindText()在IE浏览器的方法.这是一个例子:

http://jsfiddle.net/xeSQb/6/

不幸的是,Opera在转换到版本15中的Blink渲染引擎之前不支持window.find或者TextRange.如果这是您关注的问题,那么一个相当重要的替代方案是使用我的Rangy库的TextRangeCSS类应用程序模块的组合,如下面的演示:http://rangy.googlecode.com/svn/trunk/ 演示/ textrange.html

码:

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);

        while (window.find(text)) {
            document.execCommand("HiliteColor", false, "yellow");
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如何清除突出显示的单词?清除它使它恢复正常,没有亮点...... (3认同)
  • ......完成了 我也把它简洁得多了. (2认同)
  • @tim down如何删除使用上述代码突出显示的撤消突出显示.. (2认同)
  • Opera既不支持`window.find`也不支持`createTextRange`(也不支持`document.createRange()`对象的`findText`方法) (2认同)
  • 一点点更新:Opera 15和更新版本支持window.find,因为它在webkit上. (2认同)