jQuery UI自动完成,在没有结果时显示

Vic*_*tor 5 jquery-ui autocomplete

我有以下代码:

// Autocomplete search
    $("#shop_search").autocomplete({
      source: '<%= spotify_search_path(:json) %>',
      minLength: 1,
      select: function(event, ui) {
        append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web);
        $("#shop_search").val('');
      }
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li></li>" )
      .data( "item.autocomplete", item )
      .append( "<a>" + "<span class='autocomplete_link'>" + item.name + "</span>" + "<br />" + "<span class='autocomplete_address'>" + item.address_geo + "</span>" + "</a>" )
      .appendTo( ul );

      $(".ui-autocomplete-loading").ajaxStart(function(){
        $(this).show();
      });

      $(".ui-autocomplete-loading").ajaxStop(function(){
        $(this).hide();
      });

    };
Run Code Online (Sandbox Code Playgroud)

目前它只显示搜索结果时的下拉自动完成功能.我想让它显示"找不到匹配项"时找不到任何内容.我应该在代码中添加什么?

谢谢.

Chr*_*son 18

如果对源使用jQuery ajax调用,则可以在结果中附加"未找到结果"(如果没有).然后在select方法上,您只需检查项目是否是您添加的"未找到结果"项目,如果是,则不执行任何操作.在这里,我通过检查id是否等于零来确定.

$("#shop_search").autocomplete({
    source: function (request, response) {
        $.ajax({
            url: "<%= spotify_search_path(:json) %>",
            data: {
                term: request.term
            },
            success: function (data) {
                if (data.length == 0) {
                    data.push({
                        id: 0,
                        label: "No results found"
                    });
                }
                response(data);
            }
        });
    },
    select: function (event, ui) {
        if (ui.item.id != 0) {
            append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web);
            $("#shop_search").val('');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

您需要在模板上进行一些工作才能正确显示"找不到结果",但这样可以让您走上正确的轨道.