2013-03-27 38 views
9

我有以下代码。它不会产生js错误。不能得到自动完成,以显示任何结果:jquery自动完成renderItem

$(function() { 
    $.ajax({ 
    url: "data.xml", 
    dataType: "xml", 
    cache: false, 
    success: function (xmlResponse) { 
     var data_results = $("Entry", xmlResponse).map(function() { 
      return { 
       var1: $.trim($("Partno", this).text()), 
       var2: $.trim($("Description", this).text()), 
       var3: $.trim($("SapCode", this).text()), 
       var4: $("Title", this).text(), 
       var5: $.trim($("File", this).text()), 
       var6: $.trim($("ItemID", this).text()) 
      }; 
     }).get(); 

     $("#searchresults").autocomplete({ 
      source: data_results, 
      minLength: 3, 
      select: function (event, ui) { 
       ... 
      } 
     }).data("autocomplete")._renderItem = function(ul, item) { 
       return $("<li></li>").data("item.autocomplete", item) 
        .append("<a>" + item.var1 + "<br>" + item.var2 + "</a>") 
        .appendTo(ul); 
     }; 

    } 
}); 

任何想法我可能会丢失?提前致谢。

回答

5

默认情况下,自动完成预计源阵列包含与对象无论是label性质,value财产,或两者兼而有之。

考虑到这一点,你有两个选择:

  1. 添加标签或值的属性源的对象,当你处理从您的AJAX调用数组:

    var data_results = $("Entry", xmlResponse).map(function() { 
        return { 
         var1: $.trim($("Partno", this).text()), 
         var2: $.trim($("Description", this).text()), 
         var3: $.trim($("SapCode", this).text()), 
         var4: $("Title", this).text(), 
         var5: $.trim($("File", this).text()), 
         var6: $.trim($("ItemID", this).text()), 
         value: $.trim($("Description", this).text()) 
        }; 
    }).get(); 
    

    value你分配将用于focus,select,并进行搜索。

  2. 更改source功能进行自定义筛选逻辑:

    $("#searchresults").autocomplete({ 
        source: function (request, response) { 
         var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); 
    
         response($.grep(data, function (value) { 
          return matcher.test(value.var1) || 
            matcher.test(value.var2); 
          /* etc., continue with whatever parts of the object you want */ 
         })); 
        }, 
        minLength: 3, 
        select: function (event, ui) { 
         event.preventDefault(); 
         this.value = ui.var1 + ui.var2; 
        }, 
        focus: function (event, ui) { 
         event.preventDefault(); 
         this.value = ui.var1 + ui.var2; 
        } 
    }).data("autocomplete")._renderItem = function(ul, item) { 
         return $("<li></li>").data("item.autocomplete", item) 
          .append("<a>" + item.var1 + "<br>" + item.var2 + "</a>") 
          .appendTo(ul); 
    }; 
    

    请注意,这个策略,你必须实现自定义selectfocus逻辑。