admin管理员组文章数量:1354414
Suppose I have this HTML code:
<div class="person">
Mike Mulky
</div>
<div class="person">
Jenny Sun
</div>
<div class="person">
Jack Kickle
</div>
This JQuery thingy will actually filter the matching query. For example, when a user types in a textbox.
$('#userInputTextbox').keypress(function(){
$('div.person').hide().filter(':contains("'+THE_QUERY+'")').show();
});
This works! And it actually filters out the stuff. My question is: how do you highlight the words that appear in there (the query and the matching text in the DIVs)?
Suppose I have this HTML code:
<div class="person">
Mike Mulky
</div>
<div class="person">
Jenny Sun
</div>
<div class="person">
Jack Kickle
</div>
This JQuery thingy will actually filter the matching query. For example, when a user types in a textbox.
$('#userInputTextbox').keypress(function(){
$('div.person').hide().filter(':contains("'+THE_QUERY+'")').show();
});
This works! And it actually filters out the stuff. My question is: how do you highlight the words that appear in there (the query and the matching text in the DIVs)?
Share Improve this question asked Feb 19, 2010 at 0:39 TIMEXTIMEX 273k367 gold badges802 silver badges1.1k bronze badges 2- 1 By highlight do you mean changing the style (ie bg colour) or select the text ready for copying? – Andy E Commented Feb 19, 2010 at 0:44
-
Given that he's in a
keypress
event, he presumably wants to change a color. – SLaks Commented Feb 19, 2010 at 0:46
2 Answers
Reset to default 7I'd grab the jQuery highlight plugin for this. Using it in a project now to reflect AJAX search results, works great and very light/simple.
In your case just add .highlight(THE_QUERY)
in the chain.
$('#userInputTextbox').keypress(function(){
$('div.person').hide().removeHighlight()
.filter(':contains("'+THE_QUERY+'")').highlight(THE_QUERY).show();
});
Concept is easy, find the text wrap it in a <span class="highlight"></span>
, you can style .highlight
however you want. There's a .removeHighlight()
to match of course.
For a lenient jQuery highlight plugin you may want to consider http://frightanic./web-authoring/lenient-jquery-highlight-plugin/
本文标签: javascriptHow to use JQuery to highlight textStack Overflow
版权声明:本文标题:javascript - How to use JQuery to highlight text - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744022854a2577524.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论