如何将单个项目附加到jQuery UI自动完成结果集下拉列表中?

时间:2012-08-22 23:48:40

标签: jquery jquery-ui jquery-ui-autocomplete

有没有办法将一个项附加到自动完成下拉列表的末尾,该下拉菜单包含1-5个项目?我使用了open但是因为我在加载下拉列表中添加了一个微调器,它不能正常工作。

jQuery的:

$("#search").autocomplete({
  source: function(request, response) {
    response([{loading: true}]);
    return $.ajax({
      url: "/search",
      timeout: 10000,
      dataType: "json",
      data: {
        query: request.term
      },
      success: function(data) {
        var results;
        results = [];
        results = $.map(data, function(result) {
          return {
            label: result.name,
          };
        });
        return response(results);
      }
    });
  }
  //open doesn't work because I have a spinning effect that opens a dropdown
  //when the search is loading.
  //open: function() {
  //  alert('test');
  //}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
  if(item.loading) {
    return $( "<li id='spinner'></li>" )
      .appendTo( ul );
  }
};

谢谢!

1 个答案:

答案 0 :(得分:4)

在将结果列表发送到push回调之前,您应该只需response您想要的任何项目:

$("#search").autocomplete({
    source: function(request, response) {
        response([{loading: true}]);
        $.ajax({
            url: "/search",
            timeout: 10000,
            dataType: "json",
            data: {
                query: request.term
            },
            success: function(data) {
                var results = $.map(data, function(result) {
                    return {
                        label: result.name,
                    };
                });

                results.push({ label: "My Custom Item" });
                response(results);
            }
        });
    }
});

示例: http://jsfiddle.net/m3MGH/1/