静态 HTML 页面中的 JQuery 搜索,突出显示找到的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10011385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:42:50  来源:igfitidea点击:

JQuery search in static HTML page with highlighting of found word

jqueryhtmlcsssearchhighlight

提问by Radu Gheorghiu

I've been trying to make a simple search inside a static HTML page using JQuery. I have to mention that this is just my first time working with JQuery.

我一直在尝试使用 JQuery 在静态 HTML 页面中进行简单的搜索。我不得不提一下,这只是我第一次使用 JQuery。

I'm trying to change the background of the found word in the page and this is what I've tried so far:

我正在尝试更改页面中找到的单词的背景,这是我迄今为止尝试过的:

myJavascript.js:

我的Javascript.js:

$(document).ready(function(){

     $('#searchfor').keyup(function(){
         page = $('#all_text').text();
         searchedText = $('#searchfor').val();
         $("p:contains('"+searchedText+"')").css("color", "white");
    });
});

Here's the HTML code as well:

这也是 HTML 代码:

page.html:

页面.html:

<html>
<head>
    <title>Test page</title>
</head>
<body bgcolor="#55c066">
<input type="text" id="searchfor"></input>
    <p id="all_text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
    <font color="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</font>
    </p>
</body>
    <script src="jquery-1.7.2.min.js"></script>
    <script src="myJavascript.js"></script>
</html>

After inspecting the page with Firebug I can see that the variables in JQuery do get the value from the input field but I guess I'm messing up the highlighting part.

使用 Firebug 检查页面后,我可以看到 JQuery 中的变量确实从输入字段中获取了值,但我想我搞砸了突出显示部分。

Thanks in advance for your help!

在此先感谢您的帮助!

采纳答案by scibuff

Do something like this

做这样的事情

 $("p:contains('"+searchedText+"')").each( function( i, element ) {
      var content = $(element).text();
      content = content.replace( searchedText, '<span class="search-found">' + searchedText + '</span>' );
      element.html( content );
 });

 .search-found {
     text-decoration: underline;
 }

p.s. this will work only if each of the "elements" has plain text only content otherwise it would remove children nodes

ps 这只有在每个“元素”只有纯文本内容时才有效,否则它会删除子节点

EDIT: removed the extra ')' in the eachcallback

编辑:在each回调中删除了额外的 ')'

回答by dude

Why using a selfmade highlighting function is a bad idea

为什么使用自制的高亮功能是个坏主意

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

从头开始构建自己的突出显示功能可能是一个坏主意的原因是因为您肯定会遇到其他人已经解决的问题。挑战:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!
  • 您需要删除带有 HTML 元素的文本节点以突出显示您的匹配项,而不会破坏 DOM 事件并一遍又一遍地触发 DOM 重新生成(例如,就是这种情况innerHTML
  • 如果要删除突出显示的元素,则必须删除 HTML 元素及其内容,并且还必须组合拆分的文本节点以进行进一步搜索。这是必要的,因为每个荧光笔插件都会在文本节点内搜索匹配项,并且如果您的关键字将被拆分为多个文本节点,它们将不会被找到。
  • 您还需要构建测试以确保您的插件在您没有考虑过的情况下工作。我说的是跨浏览器测试!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

听起来很复杂?如果您想要一些功能,例如从突出显示、变音符号映射、同义词映射、iframe 内搜索、分隔词搜索等中忽略某些元素,这将变得越来越复杂。

Use an existing plugin

使用现有插件

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter pluginson Sitepoint compares popular highlighter plugins. This includes plugins of answers from this question.

使用现有的、实现良好的插件时,您不必担心上述命名的事情。Sitepoint 上的文章10 jQuery 文本荧光笔插件比较了流行的荧光笔插件。这包括这个问题的答案插件。

Have a look at mark.js

看看mark.js

mark.jsis such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

mark.js就是这样一个用纯 JavaScript 编写的插件,但也可以作为 jQuery 插件使用。它的开发目的是提供比其他插件更多的机会,可以选择:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms
  • 单独搜索关键字而不是完整的术语
  • 映射变音符号(例如,如果“justo”也应该匹配“justò”)
  • 忽略自定义元素内的匹配项
  • 使用自定义高亮元素
  • 使用自定义突出显示类
  • 映射自定义同义词
  • 也在 iframe 内搜索
  • 收到未找到的条款

DEMO

演示

Alternatively you can see this fiddle.

或者你可以看到这个 fiddle

Usage example:

用法示例

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

它是在 GitHub 上免费开发的开源软件(项目参考)。

Example of mark.js keyword highlighting with your code

使用代码突出显示 mark.js 关键字的示例

$(function() {
  $("input").on("input.highlight", function() {
    // Determine specified search term
    var searchTerm = $(this).val();
    // Highlight search term inside a specific context
    $("#context").unmark().mark(searchTerm);
  }).trigger("input.highlight").focus();
});
mark {
  background: orange;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<input type="text" value="test">
<div id="context">
  Lorem ipsum dolor test sit amet
</div>

回答by mshsayem

Here is mine: http://jsfiddle.net/x8rpY/1/

这是我的:http: //jsfiddle.net/x8rpY/1/

JS:

JS:

$('#searchfor').keyup(function(){
         var page = $('#all_text');
         var pageText = page.text().replace("<span>","").replace("</span>");
         var searchedText = $('#searchfor').val();
         var theRegEx = new RegExp("("+searchedText+")", "igm");    
         var newHtml = pageText.replace(theRegEx ,"<span></span>");
         page.html(newHtml);
    });

CSS:

CSS:

#all_text span
{
    text-decoration:underline;
    background-color:yellow;    
}

Works for repeated search also.

也适用于重复搜索。

回答by Rajan

$(function() {
  $("input").on("input.highlight", function() {
    // Determine specified search term
    var searchTerm = $(this).val();
    // Highlight search term inside a specific context
    $("#context").unmark().mark(searchTerm);
  }).trigger("input.highlight").focus();
});
mark {
  background: orange;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/mark.js/7.0.0/jquery.mark.min.js"></script>
<input type="text" value="test">
<div id="context">
  Lorem ipsum dolor test sit amet
</div>

回答by alxbrd

Here is another example that I quickly hacked: http://jsfiddle.net/VCJUX/

这是我快速破解的另一个示例:http: //jsfiddle.net/VCJUX/

回答by Oofpez

(for one thing you want to use Background-Color, not Color, for background)

(一方面,您想使用背景颜色,而不是颜色作为背景)

I would create a css class for normal and a seperate (inherited) css class for highlighted text, and then use the JQuery to change the css class when you find what you are looking for.

我将为普通的 css 类和用于突出显示文本的单独的(继承的)css 类创建一个 css 类,然后在找到所需的内容时使用 JQuery 更改 css 类。

Just my initial thoughts though, not sure if there is a better way of doing it.

只是我的初步想法,不确定是否有更好的方法。

EDIT: if you want to change only a specific word, you'll have to modify innerHTML to put it in a seperate tag at that point.

编辑:如果你只想改变一个特定的词,你必须修改 innerHTML 将它放在一个单独的标签中。