0

我正在实现搜索功能。但实际上我面临一些问题。第一次搜索很好。但是当我第二次搜索时它会产生问题。它没有正确搜索。?能给我个好办法吗?搜索文本。? http://jsfiddle.net/ravi1989/wjLmx/1/

function searchAndHighlight(searchTerm, selector) {
    if(searchTerm) {
        //var wholeWordOnly = new RegExp("\\g"+searchTerm+"\\g","ig"); //matches whole word only
        //var anyCharacter = new RegExp("\\g["+searchTerm+"]\\g","ig"); //matches any word with any of search chars characters
        var selector = selector || "#realTimeContents";                             //use body as selector if none provided
        var searchTermRegEx = new RegExp(searchTerm,"ig");
        var matches = $(selector).text().match(searchTermRegEx);
        if(matches!=null&&matches.length>0) {
           $('.highlighted').removeClass('highlighted');     //Remove old search highlights
                $(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
           $('.match:first').addClass('highlighted');
            $('.next_h').on('click',i=1, function()
        {  


            $('.match').removeClass('highlighted');                                                                   
            $('.match').eq(i).addClass('highlighted');

          i=i+1; 
        k=i-2;

     }); 
                  $('.previous_h').on('click',k=1, function()
        {  

          if(matches.length>k&&k>0){
            $('.match').removeClass('highlighted');                                                                   
            $('.match').eq(k).addClass('highlighted');         
          k=k-1;
            i=k+2;

          }
     });




            if($('.highlighted:first').length) {             //if match found, scroll to where the first one appears
                $(window).scrollTop($('.highlighted:first').position().top);
            }
            return true;
        }
    }
    return false;
}

$(document).on('click', '.searchButtonClickText_h', function(event) {

   $(".highlighted").removeClass("highlighted").removeClass("match");
     if(!searchAndHighlight($('.textSearchvalue_h').val())) {
            alert("No results found");
        }


});
4

0 回答 0