简体   繁体   中英

jQuery highlight all terms

I'm trying to highlight search terms but it doesn't split the words. Two words take as a one string and highlights only the string as is.

In the demo you can see that "Windows XP" is highlighted but not "Windows". What should I do so the both words are highlighted?

 $(document).ready(function() {

          $('p,a').highlight('Windows XP');

});

Thanks for you answers but I think you guys don't understand. The search term is taken from the input field so it changes. It won't be Windows XP always, it can be "sun on the beach" and I want all words to be highlighted not just "sun"

I updated the demo http://jsfiddle.net/eayan/12/

From the plugin's documentation (available here ):

You can highlight more than one text at once by running highlight with an array of terms as a first attribute. It's much faster than running the highlight function several times.

$("body p").highlight(["jQuery", "highlight", "plugin"]);

This means that you can simply use:

$('p,a').highlight(['Windows XP', 'Windows']);

Supposing you get your string with

var s = $('#myInput').val();

do

s.split(' ').forEach(function(token){
    $('p,a').highlight(token);
});

or

$("body p").highlight(s.split(' '));

Try this, it should highlight the whole string and words inside.

var searchterm = "Windows XP";
var tohighlight = searchterm.split(" ");
tohighlight.push(searchterm);
$("p,a").highlight(tohighlight);

Hopefully you are searching for this:

 var term = $('#q').val();
 $.each(term.split(" "),function(i,v){
     $('p,a').highlight(v);
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM