【问题标题】:How can I display jQuery AutoComplete results in a <table>, rather than a <ul>如何在 <table> 而不是 <ul> 中显示 jQuery AutoComplete 结果
【发布时间】:2023-03-15 03:06:01
【问题描述】:

我正在使用 jQuery UI 自动完成 1.8.11

我目前正在使用带缓存的远程模式,因此每次自动完成执行都会往返于服务器。理想情况下,我会返回我自己的 HTML 表,而不是它默认处理的 JSON。

我已经尝试按照maartenwierda 的概述实现this suggestion,但我无法让它工作。不知道是版本不兼容还是我做错了什么。

【问题讨论】:

  • 如果您返回的是内容而不是数据,那么进行客户端缓存会有点棘手,不是吗?
  • @DaveDev 我想这样做......但后来我想我可以把我想要的任何东西放在&lt;li&gt;&lt;/li&gt; 中,那么为什么要打扰&lt;table&gt;? @Michael_Haren 您需要缓存数据,而不是您将作为搜索结果呈现的内容,所以不需要。)

标签: jquery jquery-ui autocomplete


【解决方案1】:

我认为这可以帮助你,这里是js:

$(function() {
//overriding jquery-ui.autocomplete .js functions
$.ui.autocomplete.prototype._renderMenu = function(ul, items) {
  var self = this;
  //table definitions
  ul.append("<table><thead><tr><th>ID#</th><th>Name</th><th>Cool&nbsp;Points</th></tr></thead><tbody></tbody></table>");
  $.each( items, function( index, item ) {
    self._renderItemData(ul, ul.find("table tbody"), item );
  });
};
$.ui.autocomplete.prototype._renderItemData = function(ul,table, item) {
  return this._renderItem( table, item ).data( "ui-autocomplete-item", item );
};
$.ui.autocomplete.prototype._renderItem = function(table, item) {
  return $( "<tr class='ui-menu-item' role='presentation'></tr>" )
    .data( "item.autocomplete", item )
    .append( "<td >"+item.id+"</td>"+"<td>"+item.value+"</td>"+"<td>"+item.cp+"</td>" )
    .appendTo( table );
};
//random json values
var projects = [
    {id:1,value:"Thomas",cp:134},
    {id:65,value:"Richard",cp:1743},
    {id:235,value:"Harold",cp:7342},
    {id:78,value:"Santa Maria",cp:787},
    {id:75,value:"Gunner",cp:788},
    {id:124,value:"Shad",cp:124},
    {id:1233,value:"Aziz",cp:3544},
    {id:244,value:"Buet",cp:7847}
];
$( "#project" ).autocomplete({
    minLength: 1,
    source: projects,
    //you can write for select too
    focus: function( event, ui ) {
        //console.log(ui.item.value);
        $( "#project" ).val( ui.item.value );
        $( "#project-id" ).val( ui.item.id );
        $( "#project-description" ).html( ui.item.cp );
        return false;
    }
})
});

你可以看看这个fiddle

这可能也有帮助 fiddle

【讨论】:

  • 唯一的问题是,你会影响页面范围内的所有自动完成。仅将自定义行为应用于当前的自动完成很容易,这是我对您的代码的轻微优化:jsfiddle.net/sajjansarkar/bq526h67
【解决方案2】:

你为什么不像往常一样将数据返回为json并在客户端处理它们以表格格式显示:

$( "#targetinput" ).autocomplete({ .... }).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<table><tr><td>" + item.id+ " </td><td> " + item.label+ "</td></tr></table>" )
        .appendTo( ul );
};

你可以比上面的例子更有创意:/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多