我正在实现搜索功能。我发现它工作正常的链接..但是一个问题是当页面中没有找到匹配项时它没有设置警报。你能告诉我在哪里插入警报。我调试没有警报。我这样做了 .match.length() ==0 然后我显示警报但它不工作你能帮忙吗?
这是我找到代码的链接。 http://jsbin.com/umodoy/7/edit
var searchIndex = -1;
var searchTermOld ='';
$(document).ready(function(){
$('.searchbox').on('change',function(){
if($(this).val()===''){
var selector= "#realTimeContents";
$(selector+' span.match').each(function(){
$(this).replaceWith($(this).html());
});
}
searchIndex = -1;
$('.searchNext').attr("disabled", "disabled");
$('.searchPrev').attr("disabled", "disabled");
searchTermOld = $(this).val();
});
$('.searchbox').on('keyup',function(){
var selector= "#realTimeContents";
if($(this).val()===''){
$(selector+' span.match').each(function(){
$(this).replaceWith($(this).html());
});
}
if($(this).val() !== searchTermOld){
$(selector+' span.match').each(function(){
$(this).replaceWith($(this).html());
});
searchIndex = -1;
$('.searchNext').attr("disabled", "disabled");
$('.searchPrev').attr("disabled", "disabled");
}
});
$('.search').on('click',function(){
if(searchIndex == -1){
var searchTerm = $('.searchbox').val();
searchAndHighlight(searchTerm);
}
else searchNext();
if($('.match').length >1){
$('.searchNext').removeAttr("disabled");
$('.searchPrev').removeAttr("disabled");
}
});
$('.searchNext').on('click',searchNext);
$('.searchPrev').on('click',searchPrev);
});
function searchAndHighlight(searchTerm) {
if (searchTerm) {
var searchTermRegEx, matches;
var selector= "#realTimeContents";
$(selector+' span.match').each(function(){
$(this).replaceWith($(this).html());
});
try {
searchTermRegEx = new RegExp('('+searchTerm+')', "ig");
} catch (e) {
return false;
}
$('.highlighted').removeClass('highlighted');
matches = $(selector).text().match(searchTermRegEx);
if (matches !==null && matches.length > 0) {
var txt = $(selector).text().replace(searchTermRegEx, '<span class="match">$1</span>');
$(selector).html(txt);
searchIndex++;
$('.match:first').addClass('highlighted');
$(document).scrollTop($('.match').eq(searchIndex).offset().top);
return true;
}
return false;
}
return false;
}
function searchNext(){
searchIndex++;
if (searchIndex >= $('.match').length) searchIndex = 0;
$('.highlighted').removeClass('highlighted');
$('.match').eq(searchIndex).addClass('highlighted');
$(document).scrollTop($('.match').eq(searchIndex).offset().top);
}
function searchPrev(){
searchIndex--;
if (searchIndex < 0) searchIndex = $('.match').length - 1;
$('.highlighted').removeClass('highlighted');
$('.match').eq(searchIndex).addClass('highlighted');
$(document).scrollTop($('.match').eq(searchIndex).offset().top);
}