【问题标题】:How to customize the suggestion html with jQuery-Autocomplete如何使用 jQuery-Autocomplete 自定义建议 html
【发布时间】:2016-07-08 03:18:54
【问题描述】:

我正在使用此处看到的 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,它被调用了,只是没有生效,这里是sn-p:

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;
},

【问题讨论】:

  • 请使用正确的标签。 jquery-ui-autocomplete 不是您使用的。

标签: javascript html jquery


【解决方案1】:

查看source,插件只是调用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()
  });
},

【讨论】:

  • 谢谢!这是一个很好的答案。我记下了您的笔记并尝试在渲染之前进行编辑以修改容器,认为这会给我完全的渲染控制。但是这没有效果(上面更新了代码)。关于如何自定义正在呈现的内容的任何想法?谢谢!
【解决方案2】:

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

首先,formatResult 方法在beforeRender 方法之前被调用。加上插件为容器添加了内联样式属性,使容器的位置为绝对。

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

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 方法处理。

您可以以同样的方式对容器进行您想要的更改。

【讨论】:

    猜你喜欢
    • 2012-08-29
    • 2012-01-13
    • 2019-11-13
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 2023-03-20
    相关资源
    最近更新 更多