【问题标题】:jQuery Autocomplete include images in suggestion listjQuery Autocomplete 在建议列表中包含图像
【发布时间】:2015-11-16 15:37:46
【问题描述】:

我目前正在开发一个 Spring mvc 项目,在该项目中我使用 jQuery 自动完成插件从服务器呈现的 JSON 文件中加载数据。

$('#searchTerm').autocomplete({
    serviceUrl: '${ctx}/search/searchAutocomplete',
    paramName: "parameterName",
    delimiter: ",",
    transformResult: function(response) {
        return {
            suggestions: $.map($.parseJSON(response), function(item) {
                return {
                    value: item.userName + " , " + item.userId + ", " + 
                    item.pathToImageFile , data: item 
                };
             })
         };
     },

     onSelect: function (suggestion) {
          $(this).val(suggestion.data.userName);
          console.log(suggestion.data.userId);
          console.log(suggestion.data.pathToImageFile);
          window.location.href = "${ctx}/userPage?   
              userID="+suggestion.data.userId;
     }
 });

此代码按预期工作。我可以在建议列表中显示建议的数据,并且可以在选择项目时重定向到另一个页面。

我的问题是,如何使用 item.pathToImageFile 中的数据在建议列表中生成个人资料图片的图像?类似于 facebook 在您搜索时显示用户或群组的个人资料图片。

我在这里讨论了以下类似的主题:

jQuery UI - Formatting the autocomplete results. Add image possible?

Jquery UI autocomplete - images IN the results overlay, not outside like the demo

How to change rendering of dropdown in jquery ui autocomplete attached to a class?

但是,我似乎无法在我的代码中应用已接受的答案。在纯 html 和 javascript 中,我知道每个建议项的语法应该如下所示:

'<img src="'+ suggestion.data.pathToImageFile + '"/>' 
'<p>' +suggestion.data.userName + '</p>'

我似乎无法弄清楚自动完成插件的配置和内置方法。该文档根本没有帮助。希望有人可以帮助我。谢谢

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    您需要添加.data("ui-autocomplete")._renderItem = function (ul, item) { 在我的 AJAX 响应中,item.label 已经包含所需的具有正确格式的 HTML 代码(我不使用图像,而是使用其他格式)

    $('#searchTerm').autocomplete({   
        serviceUrl: '${ctx}/search/searchAutocomplete',
        paramName: "parameterName",
        delimiter: ","
    
     /* This is the part to be implemennted */
     }).data("ui-autocomplete")._renderItem = function (ul, item) {
             return $("<li></li>")
                 .data("item.autocomplete", item)
                 .append("<a>" + item.label + "</a>")
                 .appendTo(ul);
     };
    

    您需要调整代码和您的 AJAX 响应,但我认为您可以从这里获取...

    【讨论】:

    • 是的,也回顾一下我发布的链接,您的这个建议似乎是解决我的问题的公认方式。你是对的,似乎我需要更改建议容器 DOM 和 ajax 响应中的一些配置,特别是因为我从这个站点 github.com/devbridge/jQuery-Autocomplete 使用的插件在某种程度上是对官方 jquery 自动完成插件的修改。我会尽力将您的建议应用于代码,并在我做对时发布答案。非常感谢。
    【解决方案2】:

    我无法使用 jquery.autocomplete 插件,但如果你不能让它工作,Select2 插件具有此功能,并且它在 github here 上的示例页面上有很好的记录(查看"Data Sources -&gt; Loading remote data" 部分)。

    也许您可以从中获得一些见解/灵感?希望对您有所帮助!

    【讨论】:

    • 您好,谢谢您的回复。我会研究那个插件。但是作为java和jquery的初学者,我想我应该首先专注于学习基础框架。但肯定会调查这个并给你我的反馈:)
    猜你喜欢
    • 2012-01-13
    • 1970-01-01
    • 2011-06-24
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2017-02-19
    • 1970-01-01
    相关资源
    最近更新 更多