代码之家  ›  专栏  ›  技术社区  ›  Martin at Mennt

在jQuery自动完成中限制结果

  •  10
  • Martin at Mennt  · 技术社区  · 15 年前

    如何对jQuery自动完成的结果设置限制?

    这是我的代码:

            $.ajax({
                url: "/cache/search/SearchModels.xml",
                dataType: "xml",
                success: function(xmlResponse) {
                    var data = $("SearchModel", xmlResponse).map(function() {
                        return {
                            value: $("Name", this).text() + ", " + $("Description", this).text(),
                            id: $("No", this).text(),
                            name: $("Name", this).text(),
                            url: $("URL", this).text()
                        };
                    }).get();
                    $("#txtTopSearch").autocomplete({
                        source: data,
                        minLength: 2,
                        select: function(event, ui) {
                            BlockUI();
                            if (typeof (ui.item.url) != 'undefined') {
                                window.location = ui.item.url;
                            }
                            else {
                                alert('Page not found!');
                                $.unblockUI();
                            }
                        },
                        search: function(event, ui) {
                            $('#txtTopSearch').addClass('searchInProgress');
                        },
                        close: function(event, ui) {
                            $('#txtTopSearch').removeClass('searchInProgress');
                        }
                    }).data("autocomplete")._renderItem = function(ul, item) {
                        return $("<li></li>")
                        .data("item.autocomplete", item)
                        .append("<a><span style='font-size:.9em; font-weight:bold;'>" + item.id + "</span><br /><span style='font-size:.8em;'>" + item.name + "</span></a>")
                        .appendTo(ul);
                    };
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert('Error: ' + xhr.statusText);
                }
            });
    

    此代码返回查询中的所有结果,但我希望将其限制为仅显示10个结果。在旧的自动完成版本中,有一个选项可供选择,但现在已被弃用。

    XML示例:

    <?xml version="1.0"?>
    <ArrayOfSearchModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <SearchModel>
        <No>1</No>
        <Name>My product</Name>
        <Description>My description</Description>
        <Tags>blue;brown;</Tags>
        <URL>/Products/1</URL>
      </SearchModel>
    </ArrayOfSearchModel>
    
    5 回复  |  直到 15 年前
        1
  •  11
  •   Community Mohan Dere    9 年前

    最后更新

    因为你已经覆盖了默认值 _renderItem _renderMenu .

    $.ui.autocomplete.prototype._renderMenu = function( ul, items ) {
       var self = this;
       $.each( items, function( index, item ) {
          if (index < 10) // here we define how many results to show
             {self._renderItem( ul, item );}
          });
    }
    

    答案由此修改 jQueryUI: how can I custom-format the Autocomplete plug-in results? 所以谢谢你去“芝士”。。


    在你身上 success 回拨使用 $("SearchModel:lt(10)", xmlResponse).map(...

    这个 :lt(10)

    ( 当然10号可以是你想要的任何东西

    看看 :lt() 选择器位于 http://api.jquery.com/lt-selector/

    更新

    虽然我不明白为什么第一个答案不起作用,因为 SearchModel 是一个标签,我们的目标是。。我们可以在map方法中移动过滤。。

    success: function(xmlResponse) {
                    var data = $("SearchModel", xmlResponse).map(function(index) {
                        if (index<10)
                          {
                            return {
                                value: $("Name", this).text() + ", " + $("Description", this).text(),
                                id: $("No", this).text(),
                                name: $("Name", this).text(),
                                url: $("URL", this).text()
                                   };
                          }
                          else
                          { return null; }
                    }).get();
    

    documentation of map()

        2
  •  3
  •   Achilles    15 年前

    为什么不限制查询从xml源返回的数据?

    您必须记住,自动完成功能实际上是使用正则表达式来匹配数据源中的项。拥有一个大的数据源是不好的,因为它必须分析这么多的数据才能找到正确的项。

        3
  •  2
  •   Paul Sheldrake    12 年前

    这是我在阅读自动完成API文档的基础上所做的

    $input.autocomplete({
      source: function( request, response ) {
        $.getJSON('search.php', request, function( data, status, xhr ) {
          // return a max of 10 results.
          response( data.slice(0, 9) );
        });
      }
    })
    

    遵循这个模式可以省去在渲染层中做任何有趣的事情。

        4
  •  2
  •   Mirko Bianco    9 年前

    限制结果的最快方法是在“打开”事件期间执行。 我们可以删除jqueryui动态创建的部分内容,从而减少子元素数组。

    这个解决方案为我解决了同样的问题:

    var maxResults = 10;
    $input.autocomplete({
        source: somefile.json,
        open: function(event,ui){
              $(this).data("uiAutocomplete").menu.element.children().slice(maxResults).remove();
             }
    })
    
        5
  •  1
  •   sorry    14 年前

        open:function(event,ui){ 
        var maxListLength=10;
        var ul = jQuery( "#txtTopSearch" ).autocomplete("widget")[0];
        while(ul.childNodes.length > maxListLength)
              ul.removeChild(ul.childNodes[ul.childNodes.length-1]);
        }