繁体   English   中英

如何使用 jQuery-Autocomplete 自定义建议 html

[英]How to customize the suggestion html with jQuery-Autocomplete

我正在使用这里看到的 jQuery-Autocomplete 插件: https : //github.com/devbridge/jQuery-Autocomplete

我正在尝试控制作为建议呈现的项目。 默认情况下,自动完成建议如下所示:

<div class="autocomplete-suggestion" data-index="0">438</div>

我希望能够构建该项目,以便我可以执行以下操作:

<div class="autocomplete-suggestion" data-index="0">
    <div class="autocomplete-suggestion-photo"></div>
    <div class="autocomplete-suggestion-title"></div>
</div>

我正在使用被调用的 beforeRender,只是没有生效,这是片段:

beforeRender: function (container) {
  console.log(container)
  xx = '<div class="autocomplete-suggestion" data-index="1">TEST</div>';
  return xx;
},

任何想法我做错了什么?

更新了下面的代码。 想法是在 beforeRender 中更改容器以完全自定义正在呈现的内容。 这没有效果。

beforeRender: function (container) {
  console.log(container)
  container = '<div class="autocomplete-suggestion" data-index="1">TEST</div>';
  return container;
},

查看源代码,插件只是调用beforeRender ,然后显示容器:

if ($.isFunction(beforeRender)) {
  beforeRender.call(that.element, container, that.suggestions);
}

that.fixPosition();
container.show();

它不使用任何返回值。 文档说:

beforeRender :在显示建议之前调用的function (container, suggestions) {} 您可以在建议 DOM 显示之前对其进行操作。

所以我认为你应该直接操作容器,比如:

beforeRender: function (container, suggestions) {
  container.find('.autocomplete-suggestion').each(function(i, suggestion){
   // suggestion.append(); suggestion.preppend(); suggestion.whatever()
  });
},

一个老问题,但面临类似的问题。 我想在 div 中显示结果而不是默认下拉列表。 如果有人有这样的要求,想更新解决方法。

首先,该formatResult方法是在之前称为beforeRender方法。 此外,该插件向容器添加了内联样式属性,使容器的位置成为绝对位置。

现在回到最初的问题,正如@TJ 在答案中提到的,该方法不使用返回值,因此我们必须对方法本身中的容器进行更改。 这是我想出的。

beforeRender: function (container) {
    
    var html = "";
    
    //get inner html of each of the suggestion
    container.find('.autocomplete-suggestion').each(function(i, suggestion){
        html = html + $(suggestion).html();
    });
    
    //append the html to the div where you want to display the results
    $("#auto-results").html(html);
    
    /*
    * remove the inline style from the container that makes the position absolute
    * and other styles
    */
    $(container).removeAttr("style");
    
    //empty the inner html of the container
    $(container).html("");
},

这样默认的容器就不显示了,但是所有的建议都显示在我自己的容器div中。

请记住,单个建议样式由formatResult方法处理。

您可以以相同的方式对容器进行所需的更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM