2016-09-16 74 views
0

我有一個問題顯示no results。我所有的代碼都可以工作,但我不知道我應該在哪裏有if語句。jquery自動完成如何顯示'沒有結果'

我的數組:

var users = [ 
    { 
     id: '1', 
     name: 'adam' 
    }, 
    { 
     id: '2', 
     name: 'thomas' 
    }, 
    { 
     id: '3', 
     name: 'harvey' 
    }, 
    { 
     id: '4', 
     name: 'bethy' 
    } 
]; 

$("#acSearch").autocomplete({ 
    minLength: 2, 
    source: function(request, response){ 
     var check = $.ui.autocomplete.escapeRegex(request.term); 
     var match = new RegExp(check, "i"); 
     response($.grep(($.map(users, function(v, i){ 
      return { 
       id: v.id, 
       blog: v.blog 
      }; 
     })), function(item){ 
      console.log(item.blog); 
      return match.test(item.blog); 
     })); 
    }, 
    focus: function(event, ui){ 
     $("#acSearch").val(ui.item.blog); 
     return false; 
    }, 
    select: function(event, ui){ 
     $("#acSearch").val(ui.item.blog); 
     return false; 
    } 
}) 
.autocomplete("instance")._renderItem = function(ul, item){ 
    return $("<li>").append("<div>" + item.blog + "</div>").appendTo(ul); 
}; 

一切工作正常,但我試圖把一個if語句來檢查是否有匹配。

回答

0

用戶陣列的所有屬性首先是錯配博客

因此,你可以使用下面的代碼來顯示沒有結果基於你的代碼

var users = [ 
    { 
     id: '1', 
     blog: 'adam' 
    }, 
    { 
     id: '2', 
     blog: 'thomas' 
    }, 
    { 
     id: '3', 
     blog: 'harvey' 
    }, 
    { 
     id: '4', 
     blog: 'bethy' 
    } 
]; 

$("#acSearch").autocomplete({ 
    minLength: 2, 
    source: function(request, response){ 
     var check = $.ui.autocomplete.escapeRegex(request.term); 
     var match = new RegExp(check, "i");  
     var arr = jQuery.map(users, function(element, index) { 
      if(match.test(element.blog)){ 
       return element; 
      } 
     }); 
     if(arr.length == 0){ 
      arr.push({id: '',blog: ''}) 
     } 
     response(arr); 
    }, 
    focus: function(event, ui){ 
     $("#acSearch").val(ui.item.blog); 
     return false; 
    }, 
    select: function(event, ui){ 
     $("#acSearch").val(ui.item.blog); 
     return false; 
    } 
}) 
.autocomplete("instance")._renderItem = function(ul, item){ 
    if(item.id === '' && item.blog === ''){ 
     return $("<li>").append("<div>no results</div>").appendTo(ul); 
    }else{ 
     return $("<li>").append("<div>" + item.blog + "</div>").appendTo(ul); 
    } 

}; 

如果沒有匹配的數據,則_renderItem不是調用。

相關問題