我正在做文本的搜索功能。实际上我第一次搜索时遇到了一个问题,它工作正常。但是当我再次搜索并按搜索时,它显示前一个搜索突出显示的文本。不显示搜索文本。如何解决那个问题。这是我的代码。 http://jsfiddle.net/ravi1989/z7fjW/143/
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 || "#bodyContainer"; //use body as selector if none provided
var searchTermRegEx = new RegExp(searchTerm,"ig");
var matches = $(selector).text().match(searchTermRegEx);
if(matches) {
$('.highlighted').removeClass('highlighted'); //Remove old search highlights
$(selector).html($(selector).html().replace(searchTermRegEx, "<span class='match'>"+searchTerm+"</span>"));
$('.match:first').addClass('highlighted');
$('#next').on('click',i=1, function()
{ alert(i);
$('.match').removeClass('highlighted'); $('.match').eq(i).addClass('highlighted');
i=i+1;
k=i-2;
alert(i);
});
$('#previous').on('click',k=1, function()
{ alert(k);
$('.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).ready(function() {
$('#search-button').on("click",function() {
if(!searchAndHighlight($('#search-term').val())) {
alert("No results found");
}
});
});