Return 消息 - 文本框中没有结果

Return message - no results from text box

我是 jquery 的新手,希望学习。

我正在尝试开发一个搜索页面。目前,如果没有匹配项,则不会返回任何内容。我已经尝试了各种片段来添加消息,但它似乎不起作用。

有人能帮忙吗?

谢谢

 <input type="text" id="search-criteria"/><BR> 
 <input type="button" id="search" value="Policy Search"/><BR> 
 <div  class="contact-name" style='background-color:#f2f2f2'> Daniel </div> 
 <div class="contact-name" style='background-color:#f2f2f2'>david </div>



$('.contact-name').hide();
$('#search').click(function(){
$('.contact-name').hide();
var txt = $('#search-criteria').val();
$('.contact-name').each(function(){
   if($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1){
       $(this).show();
   }
});
});

您需要检查 .each 循环是否找到了一个值;如果是,则提早退出;如果不是,显示 "no results" 消息。

<!-- Add this element to the HTML. -->
<div class="no-results">There are no results available.</div>
$(".contact-name, .no-results").hide();
$("#search").click(function() {
  $(".contact-name, .no-results").hide();
  var txt = $("#search-criteria").val();
  var found = false;
  $(".contact-name").each(function() {
    if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
      $(this).show();
      found = true;
      return false;
    }
  });
  if (!found) {
    $('.no-results').show();
  }
});