获取jQuery自动完成功能以将结果显示为链接 [英] Getting jQuery autocomplete to display results as links

查看:80
本文介绍了获取jQuery自动完成功能以将结果显示为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的是jQuery的新手,尝试构建自动建议功能,但是没有运气.到目前为止,我已经看了一些教程并至少提出了可行的示例,但是我无法从服务中提取所需的确切数据.像这样的jQuery自动完成功能:

I am really new to jQuery and try to build an auto suggest functionality, but with no luck. So far I have watched a few tutorials and came up with at least working example, however I cannot extract exact data that I need from the service. The jQuery autocomplete function like this:

$(function() {
    var url = MyAutocomplete.url + "?action=search";

    $( "#author" ).autocomplete({
      minLength: 2,
      source: url,
      focus: function( event, ui ) {
        $( "#author" ).val( ui.item.label );
        return false;
      },
      select: function( event, ui ) {
        $( "#author" ).val( ui.item.label );
        $( "#author-id" ).val( ui.item.value );
        $( "#author-description" ).html( ui.item.desc );
        $( "#author-icon" ).attr( "src", "images/" + ui.item.icon );

        return false;
      }
    })
    .autocomplete( "instance" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
        .appendTo( ul );
    };
  });

服务以以下方式返回结果:

Service returns results in the following manner:

{"name":"John Doe",
"author_url":"http:\/\/example.com\/author\/john-doe\/",
"avatar":"<img alt='John Doe' src='http:\/\/example.com\/uploads\/1425487372-96x96.jpg' height='96' width='96' \/>"
}

我需要<li>项,如下所示:

<a href="http://example.com/author/john-doe">
<img src="http://example.com/uploads/1425487372-96x96.jpg/>
John Doe
</a>

非常感谢您的帮助或指导.

Any help or guidance is much appreciated.

推荐答案

第一个问题是服务器返回的JSON格式不正确,无法与autoComplete插件配合使用.该插件取决于响应中具有labelvalue属性的数据.您需要更改响应中给定的nameauthor_url属性的名称,如下所示:

The first issue you have is that the JSON being returned by your server is not in the correct format to work with the autoComplete plugin. The plugin depends on the data in the response having label and value properties. You need to change the names of the name and author_url properties given in the response, like this:

[{
    "label": "John Doe",
    "value": "http:\/\/example.com\/author\/john-doe\/",
    "avatar": "http:\/\/example.com\/uploads\/1425487372-96x96.jpg"
},{
    "label": "Jane Doe",
    "value": "http:\/\/example.com\/author\/jane-doe\/",
    "avatar": "http:\/\/example.com\/uploads\/1425487372-96x96.jpg"
}]

从那里,您只需要修改呈现功能即可读取这些属性并根据需要设置HTML格式:

From there you just need to amend the rendering function to read those properties and format the HTML as required:

.autocomplete("instance")._renderItem = function(ul, item) {
    return $("<li>")
        .append('<a href="' + item.value + '"><img src="' + item.avatar + '" />' + item.label + '</a>')
        .appendTo(ul);
};

工作示例

这篇关于获取jQuery自动完成功能以将结果显示为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆