我想使用jQuery / Java脚本搜索并突出显示文本。
示例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"
当我搜索字符串“ Good Morning”时,div1和div3中的内容都应突出显示。即。输出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>
我使用了插件https://raw.github.com/bartaz/sandbox.js/master/jquery.highlight.js将搜索到的内容包含在span中。但是只有div3高亮显示。请帮忙。
var src_str = $("#test").text(); var term = "my text"; term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*"); var pattern = new RegExp("("+term+")", "gi"); src_str = src_str.replace(pattern, "<mark>$1</mark>"); src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4"); $("#test").html(src_str);
试试这个可能对你有帮助