【问题标题】:jquery autocomplete how to show 'no results'jquery自动完成如何显示“无结果”
【发布时间】:2016-09-21 21:17:48
【问题描述】:

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

【问题讨论】:

    标签: jquery arrays autocomplete


    【解决方案1】:

    首先用户数组的name属性与blog不匹配

    因此您可以使用以下代码根据您的代码显示无结果

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多