2015-06-30 21 views
10

Yazılı bir metin girişine ve metni vurgulayan basit bir jQuery sözcük araması yapmaya çalışıyorum. Bunu birden çok kelime için nasıl yapabilirim? Bu kod sadece tek bir karakter için çalışıyor.Jquery basit arama öneri metni vurgulama

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

Bu yardımın size cevabı var mıdır? Http://stackoverflow.com/questions/8644428/how-to-highlight-text-using-javascript – Tony

+0

Bu eğitici de yararlı görünüyor: http: //www.the -art-of-web.com/javascript/search-highlight/ – Tony

+0

Bunu okumak için deneyin: http://stackoverflow.com/questions/7571117/jquery-something-like-contains-but-to-match-exactly-phrase – Teo

cevap

10

Eğer unsurların önceden tanımlanmış bir ayar sonra

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>
hedef varsa

+0

Thanks Arun yerine, sonuçlarınızı vurgulamak için '' kullanın. Bu iyi çalışıyor. ama ne yazdığımda giriş metnini sildiğimde görünen etiketleri. – Anoops

+0

@ user3927335 sorunu yeniden oluşturmak için bir durum verebilirsiniz - http://jsfiddle.net/arunpjohny/hnvzrcb3/3/ –

+0

Sadece kullanmak için daha iyi "var mysearchword = this.value;' yerine "var mysearchword = $ (" girdi: text ") val();' diğer 'input' öğelerinden de değerleri seçebilir. –

0

Kodunuzu biraz değiştirdim ve ihtiyacınız olanı elde edebiliyorum. Performanstan emin değilim.

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>')); 
    }; 
});