最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use JQuery to highlight text - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 7

I'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/

发布评论

评论列表(0)

  1. 暂无评论