jquery自动完成如何显示'无结果'

时间:2016-09-16 12:19:42

标签: jquery arrays autocomplete

我遇到问题no results。我的所有代码都有效,但我不知道我应该在哪里有if语句。

我的阵列:

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语句检查是否匹配。

1 个答案:

答案 0 :(得分: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。