Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript - Highlighting search words like Chrome with jQuery

I have recently done a very simple highlighting with jQuery and a highlight plugin. It looks like this:

$('myButton').click(function() {

$('body').highlight($('#myInputText').val());

});

But I wonder how can I do the Chrome like highlighting, I mean highlight the letters whenever I type in some letter in textbox without submitting. I think maybe use a keyup event... Any ideas?

Thanks Andy, i changed 'this[0]' to 'search[i]' in your code and it works if there is only one 'p' tag

$(document).ready(function(){
  var search = ['p', 'div', 'span'];

  $("#highlighter").bind('keyup', function(e){
    var pattern = $(this).val();

    $.each(search, function(i){
        var str = search[i];        
        var orgText = $(str).text();

        orgText = orgText.replace(pattern, function($1){
          return "<span style='background-color: red;'>" + $1 + "</span>"
        });

        $(str).html(orgText);
    });    
  });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I made quick excersise out of it, code:

    $(document).ready(function(){
    var search = ['p', 'div', 'span'];

    $("#highlighter").bind('keyup', function(e){
    var pattern = $(this).val();

    $.each(search, function(i){
        var str = this[0];        
        var orgText = $(str).text();

        orgText = orgText.replace(pattern, function($1){
          return "<span style='background-color: red;'>" + $1 + "</span>"
        });

        $(str).html(orgText);
    });    
  });
});??

link: http://jsbin.com/amica3/edit


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...