【发布时间】:2014-02-04 10:50:27
【问题描述】:
我正在使用来自this site 的代码 还有running jsfiddle。 我注意到,当您在小提琴示例中搜索时,您输入的单词将替换为实际结果,我试图将其删除,因为我只需要查找并突出显示。如果您搜索“”,我也会遇到错误,我正在尝试通过调整代码来解决它,但老实说,我不了解整个过程。非常欢迎任何帮助。
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 || "body"; //default selector is body 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='highlighted'>"+searchTerm+"</span>"));
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(), "#bass")) {
alert("No hay resultados");
}
});
});
【问题讨论】:
标签: jquery search replace highlight