使用jQuery简单文本突出显示 [英] Simple Text Highlight with jQuery
问题描述
首先,是的,我知道有很多突出的jquery插件,我见过他们,他们让我满意,但现在有一个问题,我想问一下!
First of all, YES, I know there are many highlight jquery plugins out there, I've seen them and they made me satisfied, but now there is a question for me which I want to ask!
为什么我要使用7kb的插件?这应该通过2行代码解决...
Why should I use a plugin which is 7kb? this should be solved with 2 lines of code...
这是我正在做的事情,我在我的webapp中搜索,我想突出显示匹配的部分,例如,我输入 ab
作为搜索查询,然后我将这些结果由Ajax加载到我的HTML中:
Here is what I am doing, I'm searching in my webapp and I want to highlight matching parts, for example I enter "ab
" as search query, then I will have these results loaded by Ajax into my HTML:
<div class="blah"><h3><a>Abicert</a></h3></div>
<div class="blah"><h3><a>The aboony test</a></h3></div>
<div class="blah"><h3><a>Abnormal abiba!!!</a></h3></div>
所以在上面的结果中,每个 ab
应该突出显示,例如:
So in the above results, every "ab
" should be highlighted, like:
Ab icert
ab oony test
ab oony test
Ab 正常 ab iba !!!
Ab normal ab iba!!!
所以,我的jQuery是:
So, my jQuery is:
$('.blah h3 a').each(function(){
var text = $(this).text();
var searched_text = 'ab';
// MY QUESTION HERE - How to highlight part of this text
});
我需要提及的另一件事是:用户可以输入 ab anotherquery
作为他的搜索查询,所以这应该按空格分解,并在结果中每个 ab
和另一个查询
应该突出显示。
Another thing that I need to mention is that: the User may enter "ab anotherquery
" as his search query, so this should be exploded by space, and in the results every "ab
" and "anotherquery
" should be highlighted.
我想学习这个,这不是我的事无法通过预装插件解决...
I would like to learn this, it's not a thing that I could not solve with ready plugins...
提前致谢
推荐答案
使用RegExp和 preg_quote (负责正则表达式中使用的字符)。
Use RegExp and preg_quote (which takes care of characters used in regex).
function preg_quote( str ) {
// http://kevin.vanzonneveld.net
// + original by: booeyOH
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// * example 1: preg_quote("$40");
// * returns 1: '\$40'
// * example 2: preg_quote("*RRRING* Hello?");
// * returns 2: '\*RRRING\* Hello\?'
// * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
// * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
$('.blah h3 a').each(function(){
var text = $(this).text();
var searched_text = 'ab la';
var keywords = searched_text.split(' ');
keywords = $.map(keywords, preg_quote);
$(this).html(text.replace(new RegExp("(" + keywords.join('|') + ")" , 'gi'), "<b>$1</b>"));
});
这将按空格打破搜索查询并用< b >
This will break the search query by space and wrap each match with <b>
这篇关于使用jQuery简单文本突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!