在突出显示搜索词后,我正在实现搜索功能。实际上,我还实现了下一个和上一个功能。实际上,当我运行它时,它会正确搜索这个词,并且用户会进入下一个和上一个(精细)。但是当用户第二次搜索时,它也会突出显示第一个单词。在这里,我正在实现此功能。 http://jsfiddle.net/ravi1989/wjLmx/2/
如果您检查错误:
首先搜索:sd 然后下一步。再次搜索df。您会发现它也突出显示了第一个单词。
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");
}
});