如何在jquery中从Page中搜索Text

时间:2013-07-09 12:26:48

标签: javascript jquery jquery-mobile

我正在实现搜索功能。但实际上我正面临着一些问题。第一次它搜索得很好。但是当我第二次搜索它时会产生问题。它没有正常搜索。 你能给我好方法吗?搜索文本。? 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");
        }


});

0 个答案:

没有答案