2015-06-30 13 views
10

Sto cercando di creare una semplice ricerca di parole jQuery basata su un input di testo tipo e l'evidenziazione del testo. Come posso fare questo per più parole? Questo codice funziona solo per un singolo carattere.Evidenziazione testo suggerimento ricerca semplice Jquery

Html

<input type="text"/> 

<div>John Resig 
    George Martin 
    Malcom John Sinclair 
    J. Ohn 
    Sample text 
</div> 

CSS

span {  
    background : red 
} 

JS

$("input").keyup(function() { 
    var mysearchword = $("input:text").val();  
    var word = mysearchword; 
    $("div:contains('"+word+"')").html(function(i,html) { 
     var re = new RegExp(word,"g"); 
     return html.replace(re,'<span>'+word+'</span>') 
    }); 
}); 

JsFiddle

+0

Questa risposta ti è di aiuto? Http: //stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript – Tony

+0

Questo tutorial ti sembra utile: http: //www.the -art-of-web.com/javascript/search-highlight/ – Tony

+0

Prova a leggere questo: http://stackoverflow.com/questions/7571117/jquery-something-like-contains-but-to-match-exactly-phrase – Teo

risposta

10

Se si dispone di un insieme predefinito di elementi per indirizzare poi

var $para = $('.para') 
 
$("input").keyup(function() { 
 
    $para.find('span.highlight').contents().unwrap(); 
 
    var mysearchword = this.value.trim(); 
 
    if (mysearchword) { 
 
    var re = new RegExp('(' + mysearchword.trim().split(/\s+/).join('|') + ')', "gi"); 
 
    $para.html(function(i, html) { 
 
     return html.replace(re, '<span class="highlight">$1</span>') 
 
    }); 
 
    } 
 
});
span.highlight { 
 
    background: red 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<input type="text" /> 
 
<div class="para">John Resig George Martin Malcom John Sinclair J. Ohn Sample text</div>

+0

Grazie Arun. questo funziona bene. ma i tag vengono visualizzati quando Iam elimina il testo di input che cosa ho digitato. – Anoops

+0

@ user3927335 puoi dare un caso per ricreare il problema - http://jsfiddle.net/arunpjohny/hnvzrcb3/3/ –

+0

Meglio usare semplicemente 'var mysearchword = this.value;' invece di 'var mysearchword = $ (" input: text "). val();' che potrebbe selezionare anche i valori da altri elementi 'input'. –

0

Ho modificato il codice un po 'e sono in grado di ottenere ciò di cui hai bisogno. Comunque non sono sicuro della prestazione.

Html

<input type="text" id="inputText" /> 
<div id="sampleText"> 
    John Resig George Martin Malcom John Sinclair J. Ohn Sample text 
</div> 

JS

$("input").keyup(function() { 

    var mysearchword = $(this).val(); 
    var word = mysearchword; 
    var textInDiv = $("#sampleText").text(); 
    if (textInDiv.indexOf(word) > 0) { 
     var re = new RegExp(word, "g"); 
     $("#sampleText").html(textInDiv.replace(re, '<span>' + word +'</span>')); 
    }; 
}); 
Problemi correlati