【问题标题】:JQuery Autocomplete without using label, value, id不使用标签、值、id 的 JQuery 自动完成
【发布时间】:2012-08-23 17:58:45
【问题描述】:

是否可以在不使用常规 id、label、value 的情况下让 JQuery 自动完成工作?

例如,我不想使用:

[ { "id": "Botaurus stellaris", "label": "Great Bittern", "value": "Great Bittern" }, 
{ "id": "Asio flammeus", "label": "Short-eared Owl", "value": "Short-eared Owl" }]

而是:

[ { "my_id": "Botaurus stellaris", "first_name": "Great Bittern", "last_name": "Great Bittern" }, 
{ "my_id": "Asio flammeus", "first_name": "Short-eared Owl", "last_name": "Short-eared Owl" }]

那么,JQuery autocomplete 通常采用 id,value,label,我可以让它采用 my_id, first_name, last_name 并让 Jquery Autocomplete 像 id,label,value 一样对待吗?

当我不想修改来自数据源的数据键以将其显示在 JQuery 自动完成上时,这可能很有用。

【问题讨论】:

    标签: jquery-ui jquery autocomplete


    【解决方案1】:

    没关系,

    从 JQueryUI 的自动完成示例源中找到答案:

        $( "#city" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "http://ws.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.geonames, function( item ) {
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name
                            }
                        }));
                    }
                });
            },
            minLength: 2
        });
    

    在这里,source 被分配了一个函数,它可以转换并返回任何类型的键,需要转换为 JQuery 的自动完成的id,value,label

    可能会有所帮助。

    【讨论】:

      【解决方案2】:

      还有一个更好的解决方案。它甚至记录在 jquery-ui 网站上。

      http://jqueryui.com/demos/autocomplete/#custom-data

      $("input").autocomplete({..})
      .data( "autocomplete" )._renderItem = function( ul, item ) {return $( "<li></li>" )
          .data( "item.autocomplete", item )
                  .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
                  .appendTo( ul );
          };
      

      【讨论】:

        猜你喜欢
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多