jQuery 中的搜索和突出显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19720984/
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-27 00:29:27  来源:igfitidea点击:

Search and Highlight in jQuery

javascriptjqueryhtmlhighlighting

提问by praveen

I would like to search and highlight text using jQuery/Java Script.

我想使用 jQuery/Java Script 搜索和突出显示文本。

sample HTML 1:

示例 HTML 1:

<div id="div1"><b>Good</b> <b>Morning</b> </div>
<div id="div2">Good Evening</div> 
<div id="div3">Good Morning</div>Searched String = "Good Morning"

When i search for String "Good Morning", Both the contents in div1 and div3 should get highlighted. ie. the output html should be

当我搜索字符串“早安”时,div1 和 div3 中的内容都应该突出显示。IE。输出 html 应该是

<div id="div1"><span class="highlight"><b>Good</b> <b>Morning</b> </span></div>
<div id="div2">Good Evening</div> 
<div id="div3"><span class="highlight">Good Morning</span></div>

I have used the plugin https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.jsto enclose searched content inside span. But only div3 is highlighted. Please help.

我已经使用插件https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.js将搜索的内容包含在 span 内。但只有 div3 突出显示。请帮忙。

回答by sarath

http://jsfiddle.net/UPs3V/291/

http://jsfiddle.net/UPs3V/291/

 var src_str = $("#test").text();
var term = "my text";
term = term.replace(/(\s+)/,"(<[^>]+>)*(<[^>]+>)*");
var pattern = new RegExp("("+term+")", "gi");

src_str = src_str.replace(pattern, "<mark></mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"</mark><mark>");

$("#test").html(src_str);

try this one it may help you

试试这个它可能对你有帮助

回答by praveen

demo

演示

script

脚本

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 function newNormalize(node) {
    for (var i = 0, children = node.childNodes, nodeCount = children.length; i < nodeCount; i++) {
        var child = children[i];
        if (child.nodeType == 1) {
            newNormalize(child);
            continue;
        }
        if (child.nodeType != 3) { continue; }
        var next = child.nextSibling;
        if (next == null || next.nodeType != 3) { continue; }
        var combined_text = child.nodeValue + next.nodeValue;
        new_node = node.ownerDocument.createTextNode(combined_text);
        node.insertBefore(new_node, child);
        node.removeChild(child);
        node.removeChild(next);
        i--;
        nodeCount--;
    }
 }

 return this.find("span.highlight").each(function() {
    var thisParent = this.parentNode;
    thisParent.replaceChild(this.firstChild, this);
    newNormalize(thisParent);
 }).end();
};

HTML

HTML

Search: <input type="text" id="text-search" />

<p><b>Demo </b> he new edition of KnowlEdge K12 enables your school with flexibility by wholly automating their administrative and academic processes. With IncTech's solution for K12 schools, you can. We give you an internal infrastructure so you can share school and student information. </p>

<script type="text/javascript">
$(function() {
    $('#text-search').bind('keyup change', function(ev) {
        // pull in the new value
        var searchTerm = $(this).val();

        // remove any old highlighted terms
        $('body').removeHighlight();

        // disable highlighting if empty
        if ( searchTerm ) {
            // highlight the new term
            $('body').highlight( searchTerm );
        }
    });
});
</script>

回答by Aditya Singh

Try this out:- http://jsfiddle.net/adiioo7/H7CqV/

试试这个:- http://jsfiddle.net/adiioo7/H7CqV/

You need to remove the btags from div1and in order to apply bold property you can use css property font-weight:bold.

您需要从中删除b标签div1,为了应用粗体属性,您可以使用 css 属性font-weight:bold

HTML:-

HTML:-

<div id="div1" style="font-weight:bold">Good Morning</div>
<div id="div2">Good Evening</div> 
<div id="div3">Good Morning</div>

or

或者

<div id="div1"><b>Good Morning</b></div>
<div id="div2">Good Evening</div> 
<div id="div3">Good Morning</div>

JS:-

JS:-

$("body").highlight("Good Morning");

Edit: highlightis a 3rd party jquery lib, more info here: http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

编辑:highlight是第 3 方 jquery 库,更多信息在这里:http: //johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html