简体   繁体   English

使用jQuery突出显示Chrome等搜索词

[英]Highlighting search words like Chrome with jQuery

I have recently done a very simple highlighting with jQuery and a highlight plugin. 我最近用jQuery和一个高亮插件做了一个非常简单的突出显示。 It looks like this: 它看起来像这样:

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

$('body').highlight($('#myInputText').val()); $( '身体')突出($( '#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. 但是我想知道我怎么能像Chrome一样突出显示,我的意思是每当我在文本框中键入一些字母而不提交时突出显示这些字母。 I think maybe use a keyup event... Any ideas? 我想也许可以使用一个keyup事件......任何想法?

Thanks Andy, i changed 'this[0]' to 'search[i]' in your code and it works if there is only one 'p' tag 谢谢安迪,我在你的代码中将'this [0]'更改为'search [i]',如果只有一个'p'标签,它就有效

$(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);
    });    
  });
});

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 链接: http//jsbin.com/amica3/edit

$('#myInputText').keypress(function(e) {
    switch (e.keyCode) {
        case 13: // "Enter" was pressed; handle it if you want
            return false;

        case 27: // ESC was pressed; handle it if you want
            return false;
    }

    $('body').highlight($(this).val());
});

I've edited JAndy's code so the result would match all the occurences in the text and the search would not be case-sensitive. 我编辑了JAndy的代码,因此结果将匹配文本中的所有出现,搜索不会区分大小写。 Link Hope someone finds this helpful 链接希望有人发现这有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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